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'];
Luca Davanzo
21.6k15 gold badges124 silver badges152 bronze badges
3 Answers 3
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;
}, []);
}
treeshould 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 usingJSON.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.
answered Feb 11, 2017 at 4:00
ibrahim mahrir
31.8k5 gold badges50 silver badges78 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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.]
answered Feb 11, 2017 at 3:54
Matt Mokary
7276 silver badges13 bronze badges
1 Comment
ᴀʀᴍᴀɴ
Please provide some explanation about your question , code only answers are not so useful.
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/
Comments
lang-js
'[{...}]'? 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.