如何遍历JSON对象定位特定属性并将其内容推送到数组? [英] How to traverse JSON object locating particular property and pushing its contents to array?
问题描述
我正在使用一个JSON对象,它可以在任何叶子上有一个属性 ids
。我想遍历该对象并找到 ids
属性的所有实例,并将每个id存储在一个集合中。
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.
模拟JSON对象( ids
属性可能位于更深的属性位置。)
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"
}
]
}
}
我使用以下代码遍历上面的代码JSON。
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);
上述网络如下:
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'
]
当我的代码工作时,我不相信我这样做是最有效或最好的方式。有没有更好的方法来查找 ids
属性的所有实例?也许没有传入一个数组但返回一个?或者使用 ids
数组设置回调?
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?
推荐答案
什么你没问题,但这有点短,并使用.map函数:
what you have is fine, but this is a little shorter and uses the .map function:
var jsonFile = require('./file_test.json'); // the above in my local directory
function traverse(obj) {
var ids = [];
for (var prop in obj) {
if (typeof obj[prop] == "object" && obj[prop]) {
if (prop == 'ids') {
ids = obj[prop].map(function(elem){
return elem.id;
})
}
ids =ids.concat(traverse(obj[prop]));
}
}
return ids;
}
var ids =traverse(jsonFile);
console.log('ids', ids);
这篇关于如何遍历JSON对象定位特定属性并将其内容推送到数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!