Scanning JSON data in different parent
I have an external JSON file and its phrase into a local array of objects with a structure like the following code
{
"post": {
"sample": {
"state": "neutral"
},
"demo": {
"state": "positive"
}
}
}
How can I get all value state
in all parents and store it (store in an array) or print it ( console.log
)
I want to get the result as ["neutral", "positive"]
Node.js or JS solution is welcome
source to share
You can use an iterative and recursive approach, iterating over all properties and checking if there is one key state
, and then collecting the value. If the property is an object, then the states should be collected from the property with recursion.
function getStates(o) {
return Object.keys(o).reduce(function (r, k) {
if (o[k] && typeof o[k] === 'object') {
return r.concat(getStates(o[k]));
}
if (k === 'state') {
r.push(o.state);
}
return r;
}, []);
}
var object = { post: { sample: { state: "neutral" }, demo: { state: "positive" } } };
console.log(getStates(object));
For a dynamic key use variable, you can use another parameter for it. This means that you need to insert a key for each callback.
function getStates(o, label) {
return Object.keys(o).reduce(function (r, k) {
if (o[k] && typeof o[k] === 'object') {
return r.concat(getStates(o[k], label));
// ^^^^^ call with label
}
if (k === label) {
r.push(o[label]);
}
return r;
}, []);
}
var object = { post: { sample: { state: "neutral" }, demo: { state: "positive" } } };
console.log(getStates(object, 'state'));
To get the parent, you can store the value path and accept it as the value.
function getStates(o, p, q) {
p = p || [],
q = q || {};
Object.keys(o).forEach(function (k) {
var t = p.concat(k);
if (o[k] && typeof o[k] === 'object') {
getStates(o[k], t, q);
return;
}
q[o.state] = t.join('.');
});
return q;
}
var object = { post: { sample: { state: "neutral" }, demo: { state: "positive" } } };
console.log(getStates(object));
source to share
If your json structure will always be the same then you can use the following snippet
let obj = {
"post": {
"sample": {
"state": "neutral"
},
"demo": {
"state": "positive"
}
}
};
for(let p in obj.post){
console.log(obj.post[p].state)
}
source to share