简体   繁体   English

合并和展平数组的元素

[英]Combine and flatten elements of array

With the below JSON content that is actually coming from an API but I'm using a json file for testing.下面的 JSON 内容实际上来自 API 但我使用 json 文件进行测试。 I would like to combine the primary key and flatten the ItemList.我想组合主键并展平ItemList。

[{
        "PrimaryKey": "123",
        "ItemList": [
            {
                "SecondaryKey": "ABC",
                "Name": "Item1",
                "Description": "Sample item"
            },
            {
                "SecondaryKey": "DEF",
                "Name": "Item2",
                "Description": "Another sample item"
            }
        ],
        "IgnoreThis": [
            {
                "SomeData": "Some Data"
            }
        ]
    }]

The output I would like is:我想要的 output 是:

    [{
        "PrimaryKey": 123,
        "SecondaryKey": "ABC",
        "Name": "Item1",
        "Description": "Sample Item"
    },
    {
        "PrimaryKey": 123,
        "SecondaryKey": "DEF",
        "Name": "Item2",
        "Description": "Another sample item"
    }]

I've got the Item list being flattened by:我的项目列表被扁平化:

let items = [];
items.push(JSON.parse(fs.readFileSync('./items.json')));
let result = items.reduce((r, obj) => r.concat(obj.ItemList), []);

I've tried to use items.map to get the desired output nothing has worked, I don't think I understand how to chain.map and.reduce effectively as I get undefined as the result.我尝试使用 items.map 来获得所需的 output 没有任何效果,我认为我不明白如何链接。map 和.reduce 有效地得到未定义的结果。

Any ideas how I can achieve this output?有什么想法可以实现这个 output?

You can do this by running map twice: get the PrimaryKey from the first map, then add it to all the objects inside the second map, then you flatten the array you got from the previous stage.您可以通过运行map两次来做到这一点:从第一个 map 获取PrimaryKey ,然后将其添加到第二个 map 内的所有对象中,然后展平从前一个阶段获得的数组。

 const data = [ { PrimaryKey: "123", ItemList: [ { SecondaryKey: "ABC", Name: "Item1", Description: "Sample item", }, { SecondaryKey: "DEF", Name: "Item2", Description: "Another sample item", }, ], IgnoreThis: [ { SomeData: "Some Data", }, ], }, { PrimaryKey: "456", ItemList: [ { SecondaryKey: "ABC", Name: "Item1", Description: "Sample item", }, { SecondaryKey: "DEF", Name: "Item2", Description: "Another sample item", }, ], IgnoreThis: [ { SomeData: "Some Data", }, ], }, ]; const result = data.map(({ PrimaryKey, ItemList }) => ItemList.map(item => ({ PrimaryKey, ...item, }))).flat(); console.log(result);

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

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