Reputation: 23
Need some help to solve basic task.
I have two arrays of objects.
const firstArr = [
{id: 1, action: 'pending'},
{id: 2, action: 'pending'},
{id: 3, action: 'pending'},
];
const secondArr = [
{id: 1, action: 'accepted'},
{id: 2, action: 'accepted'},
{id: 3, action: 'accepted'},
{id: 566, action: 'accepted'},
{id: 333, action: 'accepted'},
{id: 234, action: 'accepted'},
];
I need to find in second array all objects with equal ids from first array and change "action" property in second array on "action" property from first array
Upvotes: 0
Views: 49
Reputation: 3302
You could use Map Object
. Traverse the first array and set id as key and action as a value into Map Object. Then traverse the second array and look for id in the Map Object. If id is found then change the action.
const firstArr = [
{ id: 1, action: 'pending' },
{ id: 2, action: 'pending' },
{ id: 3, action: 'pending' },
];
const secondArr = [
{ id: 1, action: 'accepted' },
{ id: 2, action: 'accepted' },
{ id: 3, action: 'accepted' },
{ id: 566, action: 'accepted' },
{ id: 333, action: 'accepted' },
{ id: 234, action: 'accepted' },
];
const map = new Map();
firstArr.forEach(({ id, action }) => map.set(id, action));
const ret = secondArr.map((x) =>
map.has(x.id) ? { ...x, action: map.get(x.id) } : { ...x }
);
console.log(ret);
Upvotes: 1
Reputation: 386578
You could gather all actions and map a new object with the wanted values.
const
firstArr = [{ id: 1, action: 'pending' }, { id: 2, action: 'pending' }, { id: 3, action: 'pending' }],
secondArr = [{ id: 1, action: 'accepted' }, { id: 2, action: 'accepted' }, { id: 3, action: 'accepted' }, { id: 566, action: 'accepted' }, { id: 333, action: 'accepted' }, { id: 234, action: 'accepted' }],
states = Object.fromEntries(firstArr.map(({ id, action }) => [id, { action }])),
result = secondArr.map(o => ({ ...o, ...states[o.id] }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0
Reputation: 7905
Here is one way to do that
const firstArr = [
{id: 1, action: 'pending'},
{id: 2, action: 'pending'},
{id: 3, action: 'pending'},
];
const secondArr = [
{id: 1, action: 'accepted'},
{id: 2, action: 'accepted'},
{id: 3, action: 'accepted'},
{id: 566, action: 'accepted'},
{id: 333, action: 'accepted'},
{id: 234, action: 'accepted'},
];
secondArr.forEach((item, index) => {
const fa = firstArr.find(i => i.id === item.id);
if(fa)
secondArr[index].action = fa.action
})
console.log(secondArr)
Loop through the second array, try to find a corresponding element in the first array and then, if found, grab its action and assign to to the proper index of the second array. Pretty basic, as you pointed out.
Upvotes: 0