简体   繁体   English

用嵌套的对象列表展平对象列表

[英]flatten a list of objects with nested lists of objects

I have a javascript list in the form of: 我有以下形式的JavaScript列表:

var list = [{id:1, data: "string", list: [
              {id:2, data: "string", list: [
                {id:3, data: "string", list: null}]},
              {id:4, data: "string", list: null}]}];

And I want it to be in the form of: 我希望它采用以下形式:

var list = [{id:1, data: "string", list: \\ original nested list or null, I don't care},
            {id:2, data: "string", list:},
            {id:3, data: "string", list:},
            {id:4, data: "string", list:}];

I have access to underscore.js, but I haven't been able to produce the output I want. 我可以访问underscore.js,但无法生成所需的输出。 I tried using a combination of _.flatten and _.pluck to get the underlying list, but I also need the id property so this doesn't work. 我尝试使用_.flatten_.pluck的组合来获取基础列表,但是我还需要使用id属性,因此这不起作用。 My guess is that I need to map a function, but I'm kind of lost on the issue right now. 我的猜测是我需要映射一个函数,但是现在我有点迷失了。

Could anybody help me with this? 有人可以帮我吗?

You can use recursion to do it: 您可以使用递归来做到这一点:

function flatten(arr) {
    if (!arr) {
        return [];
    }
    return arr.reduce(function (r, i) {
        return r.concat([i]).concat(flatten(i.list));
    }, []);
}

console.log(flatten(list));

With ES6 syntax (arrow functions and spread operator) it could look like this: 使用ES6语法(箭头函数和传播运算符),可能看起来像这样:

function flatten(arr) {
    return arr ? arr.reduce((r, i) => [...r, i, ...flatten(i.list)], []) : [];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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