Skip to content

Instantly share code, notes, and snippets.

@tafaust
Last active May 12, 2022 09:11
Show Gist options
  • Save tafaust/824c6ccbcd0f82f0d903f33df8e9e2cd to your computer and use it in GitHub Desktop.
Save tafaust/824c6ccbcd0f82f0d903f33df8e9e2cd to your computer and use it in GitHub Desktop.
Javascript filter object by object with mutation
const a = [
{id: 1},
{id: 4},
{id: 8},
{id: 6},
];
const b = [
{id: 1, op: 'foo'},
{id: 2, op: 'abc'},
{id: 3, op: 'def'},
{id: 4, op: 'ghi'},
{id: 5, op: 'jkl'},
{id: 6, op: 'mno'},
{id: 7, op: 'pqr'},
]
const res = a.reduce((accumulator, objA) => {
const foundObj = b.find(objB => objB.id === objA.id)
return foundObj === undefined ? accumulator : [...accumulator, {...objA, raqi: `${foundObj.op} :)`}];
}, []);
console.log(res);
/*
[
{ id: 1, raqi: 'foo :)' },
{ id: 4, raqi: 'ghi :)' },
{ id: 6, raqi: 'mno :)' }
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment