繁体   English   中英

从 javascript 树对象创建列表数组?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM