Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
68
rated 0 times [  74] [ 6]  / answers: 1 / hits: 15385  / 11 Years ago, sat, april 13, 2013, 12:00:00

I am working with a JSON object which can have a property ids at any leaf. I want to traverse the object and find all of the instances of the ids property and store each id in a collection.



Mocked up JSON Object (the ids property could be at much deeper property locations).





{
id: b38a683d-3fb6-408f-9ef6-f4b853ed1193,
foo: {
ids: [
{
id: bd0bf3bd-d6b9-4706-bfcb-9c867e47b881
},
{
id: d1cc529d-d5d2-4460-b2bb-acf24a7c5999
},
{
id: b68d0c8c-548e-472f-9b01-f25d4b199a71
}
],
baz: super
},
bar: {
ids: [
{
id: bd0bf3bd-d6b9-4706-bfcb-9c867e47b881
},
{
id: d1cc529d-d5d2-4460-b2bb-acf24a7c5999
},
{
id: b68d0c8c-548e-472f-9b01-f25d4b199a71
}
]
}
}


I am using the following code to traverse the above JSON.



var jsonFile = require('./file_test.json'); // the above in my local directory

function traverse(obj, ids) {
for (var prop in obj) {
if (typeof obj[prop] == object && obj[prop]) {
if (prop == 'ids') {
for (var i = obj[prop].length - 1; i >= 0; i--) {
ids.push(obj[prop][i]._id);
};
}
traverse(obj[prop], ids);
}
}
}

var ids = new Array();
traverse(jsonFile, ids);

console.log('ids', ids);


The above nets the following:



ids
[
'b68d0c8c-548e-472f-9b01-f25d4b199a71',
'd1cc529d-d5d2-4460-b2bb-acf24a7c5999',
'bd0bf3bd-d6b9-4706-bfcb-9c867e47b881',
'b68d0c8c-548e-472f-9b01-f25d4b199a71',
'd1cc529d-d5d2-4460-b2bb-acf24a7c5999',
'bd0bf3bd-d6b9-4706-bfcb-9c867e47b881'
]


While my code works I am not convinced that I am doing this the most efficient or best way. Is there a better way to find all instances of the ids property? Perhaps without passing in an array but returning one? Or setting up for a callback with an ids array?


More From » json

 Answers
19

If the data was actually a JSON string, and not a JavaScript object, you could have something like:



// assuming `json` is the data string
var ids = [];
var data = JSON.parse(json, function(key, value) {
if (key === id)
ids.push(value);

return value;
});


See reviver on JSON.parse method.


[#78930] Friday, April 12, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
parker

Total Points: 259
Total Questions: 109
Total Answers: 97

Location: Zambia
Member since Thu, Jun 25, 2020
4 Years ago
;