I have 2 sets of data arrays coming from 2 separate API calls
const data1 = [
{
name: 'John',
age: 30,
id: 1,
},
{
name: 'Sarah',
age: 28,
id: 2,
},
];
const data2 = [
{
status: 'active',
interest: "photography",
id: 1,
},
{
status: 'inactive',
interest: "traveling",
id: 2,
},
];
This is the current method I am using, but it combines the entire object from data2 to data1 if their ids match
const mergedData = data2.reduce((accumulator, current) => {
accumulator[current.id] = current;
return accumulator;
}, {});
const updatedData = data1.map((d) =>
Object.assign(d, mergedData[d.id])
);
The resulting combined data is:
{
name: 'John',
age: 30,
id: 1,
status: "active",
interest: "photography"
},
{
name: 'Sarah',
age: 28,
id: 2,
status: "inactive",
interest: "traveling"
},
I want to transfer only the status property from the second set of data arrays into the first set where the objects' ids match
Expected outcome:
const newData = [
{
name: 'John',
age: 30,
id: 1,
status: "active"
},
{
name: 'Sarah',
age: 28,
id: 2,
status: "inactive"
},
];