i have this kind of tree array, here is the actual data of my array https://pastebin.com/xtfpyKiE
there is id,parent_id, and value on each item,
id:1,
name:A,
value:0
|
----id:2
parent:1,
name:B,
value : 10
|
------id:3,
parent:2,
name :C,
value : 12
|
------id:4,
parent:3,
name :D,
value : 14
how to sum the value by parent id, from the bottom child to the top parent,
so i can get the value of A : 36, value of B : 36, value of C : 26,
thank you,
You can use destructuring assignment to get nested properties of object and assign retrieved values to an array in sequence. Use a loop to .splice()
two elements at a time from array to create object having A:36,B:36,C:26
pairs, push object back to array.
const data = {id:1, name:"A", value:0 , parent:{id:2, name: "B", value: 10 , parent:{id:3, name: "C", value: 12 , parent:{id:4, name: "D", value: 14} } } }; let res = []; ({name:res[res.length], value:res[res.length] , parent:{ name:res[res.length], value:res[res.length] , parent:{ name:res[res.length], value:res[res.length] , parent:{ name:res[res.length], value:res[res.length]}}}} = data); let k = res.length / 2; while (res.length > k) { let [key, prop] = res.splice(0, 2); res.push({[key]:prop + (res[1] && !isNaN(res[1]) && res[1] || 0) + (res[3] && !isNaN(res[3]) && res[3] || 0) + (res[5] && !isNaN(res[5]) && res[5] || 0) }); } // A : 36, value of B : 36, value of C : 26 console.log(res)
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.