provides utility methods for traversing a JSON object and performing checks or returning values from leaf nodes
npm install any-leaf``javascript
import { getLeaves } from "any-leaf";
const test = {
a: {
i: {
p: [ 'value1', { test: 'value2'}]
q: {
x: 12,
y: null
}
}
},
b: [
{ i: 'value3' },
{ i: 'value4', j: ['value5']}
]
};
const result = getLeaves
console.log(JSON.stringify())
//[
// {
// "path": "a.i.p.0",
// "value": "value1"
// },
// {
// "path": "a.i.p.1.test",
// "value": "value2"
// },
// {
// "path": "a.i.q.x",
// "value": 12
// },
// {
// "path": "a.i.q.y",
// "value": null
// },
// {
// "path": "b.0.i",
// "value": "value3"
// },
// {
// "path": "b.1.i",
// "value": "value4"
// },
// {
// "path": "b.1.j.0",
// "value": "value5"
// }
//]
`
`javascript`
const include = [ 'a.i.p', 'b'] // same for exclude, will exclude all nodes under the listed paths
`javascript`
anyLeaf(test, leaf => leaf.value === 'value1') // true
anyLeaf(test, leaf => leaf.value === 'someValNotALeaf') // false
`javascript`
allLeaves(test, leaf => leaf.value === 'value1') // false
allLeaves(test, leaf => leaf.value !== undefined) // true
`javascript`
anyLeafTruthy(test) // true
`javascript`
allLeavesTruthy(test) // false, a.i.q.y === null
`javascript`
anyLeafFalsey(test) // true, a.i.q.y === null
`javascript`
allLeavesFalsey(test) // false
`javascript`
getLeaves(test) // false
`javascript`
mapLeaves(test, leaf => ( myProp: 'my ' + leaf.value ))
`javascript``
const myArray = []
visitLeaves(test, leaf => myArray.push(leaf))