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'];
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'];
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.
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.]
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/
'[{...}]'? Remove the quotes'[ .... ]', the'quote doesn't support multi-line string and there is no reason to do that. It's not supported to be a big string, and will not function right if you have it like that.