Home > Software design >  How to merge objects of arrays? mixed key
How to merge objects of arrays? mixed key

Time:02-14

  [
        {
            "_id": "6205576aaa478f466cca3809",
            "age": 51,
            "createdAt": "2022-02-10T18:20:26.451Z",
        },
        {
            "score": [
                0,
                1,
                3,
                1,
                0,
                2
            ],
            "_id": "62081d1bc83c452ef8e34e47",
            "key_findings": "Lorem ipsum",
            "subject": "6205576aaa478f466cca3809",
            "createdAt": "2022-02-12T20:48:27.574Z",
        }
    ]

What I want it to look like:

[
  {
    _id: 6205576aaa478f466cca3809,
    age: 51,
    createdAt: 2022-02-10T18:20:26.451Z,
    score: [ 0, 1, 3, 1, 0, 2 ],
    _id: 62081d1bc83c452ef8e34e47,
    description: 'XR CHEST AP PORTABLE',
    key_findings: 'Lorem impusm',
    subject: 6205576aaa478f466cca3809,
    createdAt: 2022-02-12T20:48:27.574Z,
  }
]

I tried everything I can. There are many examples on the internet but that works only if the object's keys are the same.

CodePudding user response:

You would use object spread in the iteration of the array:

let merged={}
arr.map(item=> merged={...merged,...item})

"arr" is your array and merged is your expected answer

CodePudding user response:

As there are two properties _id they will only be one property which will remain. You can not have multiple key inside of an object with the same name.

Here is the code to merge all object as a single object you can take advantage of Array.prototype.reduce

let data = [
    {
        "_id": "6205576aaa478f466cca3809",
        "age": 51,
        "createdAt": "2022-02-10T18:20:26.451Z",
    },
    {
        "score": [
            0,
            1,
            3,
            1,
            0,
            2
        ],
        "_id": "62081d1bc83c452ef8e34e47",
        "key_findings": "Lorem ipsum",
        "subject": "6205576aaa478f466cca3809",
        "createdAt": "2022-02-12T20:48:27.574Z",
    }
];

const result = data.reduce((accumulator, item) => {
  return [{...accumulator[0], ...item}];
}, []);

console.log(result);

CodePudding user response:

I think an object not allow exist repeated key, old one will be covered

  • Related