I need to merge two arrays of different structures to one based on a field value matching to a field of type array.
Here is the example of first array
[{
"id": "1",
"name" : "one"
},{
"id": "2",
"name" : "two"
},{
"id": "3",
"name" : "three"
}]
And the example of the second array
[{ num: [ '1', '5', '7' ], alph: 'AAA' },
{ num: [ '0', '2' ], alph: 'BBB' },
{ num: [ '-1', '3', '6' ], alph: 'CCC' }]
Expecting the output like
[{
"id": "1",
"name": "one",
"alph": "AAA"
}, {
"id": "2",
"name": "two",
"alph": "BBB"
}, {
"id": "3",
"name": "three",
"alph": "CCC"
}]
CodePudding user response:
You could generate an object with all new properties grouped by id
and then map the objects with additional properties, if exist.
const
data = [{ id: "1", name: "one" }, { id: "2", name: "two" }, { id: "3", name: "three" }],
update = [{ id: [ '1', '5', '7' ], alph: 'AAA' }, { id: [ '0', '2' ], alph: 'BBB' }, { id: [ '-1', '3', '6' ], alph: 'CCC' }],
ids = update.reduce((r, { id, ...o }) => {
id.forEach(k => r[k] = { ...r[k], ...o });
return r;
}, {}),
result = data.map(o => ({ ...o, ...ids[o.id] }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
CodePudding user response:
This is a very contrived way to do this where knowledge of the structure is required and therefore brittle, but this works:
const idArr = [{
"id": "1",
"name" : "one"
},{
"id": "2",
"name" : "two"
},{
"id": "3",
"name" : "three"
}];
const numArr = [{ num: [ '1', '5', '7' ], alph: 'AAA' },
{ num: [ '0', '2' ], alph: 'BBB' },
{ num: [ '-1', '3', '6' ], alph: 'CCC' }];
function merge(arr1, arr2) {
return arr1.map((item, i) => {
item.alph = arr2[i].alph;
return item;
});
}
console.log(merge(idArr, numArr));