简体   繁体   中英

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. I would like to combine the primary key and flatten the 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:

    [{
        "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.

Any ideas how I can achieve this 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.

 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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