[英]create list array from javascript tree object?
我有 javascript 樹對象,我想將它轉換為列表數組
我的樹:
如何獲取“href”值並將其推送到數組列表?
var res=['hrefValue','hrefValue','hrefValue','hrefValue','hrefValue','hrefValue'];
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.]
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
應該是一個數組而不是一個字符串,如果你把它作為一個字符串(JSON 字符串)那么你必須在使用JSON.parse
將它傳遞給函數之前解析它。
Javascript 沒有 ArrayLists,它只有數組。
這是Array.prototype.reduce文檔的鏈接。
這是一個工作小提琴。
您可以使用Array.prototype.map()
,展開元素
let res = [];
tree.map(({href, nodes}) => res = [...res, href, ...nodes.map(({href:h}) => h)]);
// do stuff with `res`
jsfiddle https://jsfiddle.net/4ajr1spr/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.