Reputation: 957
i have javascript tree object and i want to convert it to list array
My tree:
how to get 'href' value and push it to an array list ?
var res=['hrefValue','hrefValue','hrefValue','hrefValue','hrefValue','hrefValue'];
Upvotes: 0
Views: 2531
Reputation: 1
You can use Array.prototype.map()
, spread element
let res = [];
tree.map(({href, nodes}) => res = [...res, href, ...nodes.map(({href:h}) => h)]);
// do stuff with `res`
jsfiddle https://jsfiddle.net/4ajr1spr/
Upvotes: 1
Reputation: 31712
function convert(tree){
return tree.reduce(function(acc, o) { // check the docs for reducs in the link bellow
if(o.href) // if this object has an href
acc.push(o.href); // add the href to the result array
if(o.nodes) // if this object has children
acc = acc.concat(convert(o.nodes)); // get their href and add (concat) them to the result
return acc;
}, []);
}
tree
should be an array not a string, if you have it as a string (JSON string) then you have to parse it before passing it to the function using JSON.parse
.
Javascript doesn't have ArrayLists, it only have arrays.
Here is the link to the docs of Array.prototype.reduce.
Here is a working fiddle.
Upvotes: 1
Reputation: 727
var getHrefs = function(nodes) {
return nodes.reduce(function (arr, node) {
return arr.concat(node.href).concat(node.nodes ? getHrefs(node.nodes) : []);
}, []);
}
var hrefs = getHrefs(tree); // ["7400.34.03.00.00.00", "7400.34.03.01.00.00", ... etc.]
Upvotes: 1