Pick then flatten a nested array in Javascript -
i want build generic function able extract property object unlimited nested array.
1st example
var jsonobject= { level1 : [ { id:123, level2 : [ {id:234, level3 : 'abc'}, {id:234, level3 : 'cde'} ] }, { id:123, level2 : [ {id:234, level3 : 'efg'}, {id:234, level3 : 'ghk'} ] } ] }
extractproperty : 'level1.level2.level3' (the function should able support unlimited level depends on this)
expected output (string) : 'abc,cde,efg,ghk'
2nd example
var jsonobject= { level1 : [ { id:123, level2 : 'abc'}, { id:123, level2 : 'cde'} ] }
extractproperty : 'level1.level2'
expected output (string) : 'abc,cde'
here's simple recursive solution 2 examples gave. there edge cases fails though.
const jsonobject = { level1 : [ { id:123, level2 : [ {id:234, level3 : 'abc'}, {id:234, level3 : 'cde'} ] }, { id:123, level2 : [ {id:234, level3 : 'efg'}, {id:234, level3 : 'ghk'} ] } ] }; function extractproperty(root, path) { return extractpropertyrecurse(root, path.split("."), 0).join(","); } function extractpropertyrecurse(root, levels, index) { if (array.isarray(root)) { return [].concat(...root.map(x => extractpropertyrecurse(x, levels, index))); } const curr = root && levels[index] && root[levels[index]]; if (curr) { return extractpropertyrecurse(curr, levels, index + 1) } return [root]; } const results = extractproperty(jsonobject, "level1.level2.level3") console.log(results); // out: "abc,cde,efg,ghk"
Comments
Post a Comment