[英]Get value of property from an array of objects with childs
我有一个对象数组,每个对象都有他的子对象,如下所示:
var array = [{
name: "name",
children: {
name: "namename",
children: {
name: "namenamename",
prop: "56"
}
},
...
},
...
]
现在我想获取字段“ prop”的值,但是我想从主要对象,其子代或子代子代中实现:
假设我有功能:
var get = function(obj) {
...
}
我可以发送到此功能:
get(array[0])
get(array[0].children[0])
get(array[0].children[0].children[0])
我不想为此编写三个函数,如何用一个get()函数来做到这一点?
我想从对象中获取“ prop”字段,并且每个孩子的孩子的“ prop”都相同。 所以在上面的例子中,如果我用
array[0] //or
array[0].children //or
array[0].children[0].children[0] //or
array[0].children[1].children[0] //or
array[0].children[0].children[1]
我应该始终获得相同的道具价值。 我需要具有将在整个对象中搜索的功能,但是我不知道我是否将此函数称为frm父级或其子级或child的子级
假设所有children
属性都是数组,并且收集了具有给定名称的所有属性,则此提议应该起作用。
function getProp(array, prop) { var r = []; array.forEach(function (a) { if (prop in a) { r.push(a[prop]); } if (Array.isArray(a.children)) { r = r.concat(getProp(a.children, prop)); } }); return r; } var array = [{ name: "name", children: [{ name: "namename", children: [{ name: "namenamename", prop: "56" }] }] }], prop = getProp(array, 'prop'); document.write('<pre>' + JSON.stringify(prop, 0, 4) + '</pre>');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.