简体   繁体   English

从带有子项的对象数组中获取属性的值

[英]Get value of property from an array of objects with childs

I've an array of objects, and every object has his children, like this: 我有一个对象数组,每个对象都有他的子对象,如下所示:

var array = [{
    name: "name",
    children: {
            name: "namename",
            children: {
                    name: "namenamename",
                    prop: "56"
            }
    },
    ...
 },
...
]

Now i want to get value of field 'prop', but i want to do this from main object, its children or children of children: 现在我想获取字段“ prop”的值,但是我想从主要对象,其子代或子代子代中实现:

let's say i've function: 假设我有功能:

var get = function(obj) {
    ...
}

and i can send to this function: 我可以发送到此功能:

get(array[0])
get(array[0].children[0])
get(array[0].children[0].children[0])

I dont want to write three functions for that, how can i do this with one get() function? 我不想为此编写三个函数,如何用一个get()函数来做到这一点?

I want to get "prop" field from object, and "prop" for every child of child is the same. 我想从对象中获取“ prop”字段,并且每个孩子的孩子的“ prop”都相同。 So in above example if i call function get() with 所以在上面的例子中,如果我用

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] 

i should get always the same value of prop. 我应该始终获得相同的道具价值。 I need to have function that will search in entire object, but i dont know if i call this function frm parent or its child or child of child 我需要具有将在整个对象中搜索的功能,但是我不知道我是否将此函数称为frm父级或其子级或child的子级

Assuming, that all children properties are arrays and all properties with a given name are collected, then this proposal should work. 假设所有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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM