简体   繁体   中英

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:

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?

I want to get "prop" field from object, and "prop" for every child of child is the same. 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

Assuming, that all children properties are arrays and all properties with a given name are collected, then this proposal should work.

 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>'); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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