js-select
js-select uses js-traverse to traverse and modify JavaScript object nodes that match JSONSelect selectors:
var people = {
george: {
age : 35,
movie: "Repo Man"
},
mary: {
age: 15,
movie: "Twilight"
}
}
select(people, ".age").forEach(function(age) {
this.update(age - 5);
})
select(people, ".age").nodes();
See js-traverse for all the things you can do to modify the node. The forEach()
callback will get the same this
context as the forEach()
callback from js-traverse, plus a this.matches()
which will test if the node matches a selector:
select(obj).forEach(function(node) {
if (this.matches(".mary > .movie")) {
this.remove();
}
}
selectors
js-select supports the following JSONSelect selectors:
*
type
.key
.ancestor .key
.parent > .key
.sibling ~ .key
:root
:nth-child(n)
:nth-child(even)
:nth-child(odd)
:nth-last-child(n)
:first-child
:last-child
:only-child
:has(selector)
:val("string")
:contains("substring")
See details on each selector, and try them out on the JSONSelect website.
install
For node, install with npm:
npm install js-select
For the browser, download the select.js file or fetch the latest version from npm and build a browser file using browserify:
npm install browserify -g
npm install js-select
browserify --require js-select --outfile select.js
this will build a browser file with require('js-select')
available.
propers
Huge thanks to @substack for the ingenious js-traverse and @lloyd for the ingenious JSONSelect spec and selector parser.