Javascript compare key of dictionary in arrays

Viewed 364

I've got two arrays with dictionaries like this:

var arr1 = [
    {id: 1, key1: "hello", key2: "world"},
    {id: 2, key1: "some", key2: "value"},
    {id: 3, key1: "...", key2: "..."}
]
var arr2 = [
    {id: 2, key1: "new", key2: "val"},
    {id: 5, key1: "...", key2: "..."}
]

I'd like to create a loop which takes all values of the arr1, but takes the value of arr2 if the id exists there. The result would look like this:

var result = [
    {id: 1, key1: "hello", key2: "world"},
    {id: 2, key1: "new", key2: "val"},
    {id: 3, key1: "...", key2: "..."}
]

I've tried it with the following loop, which should check if the arr2 contains the id of the current Object in arr1. This is working, when there's only 1 entry in my arrays with a matching id. But when there are 2+ matches it's not working anymore.

var result = []
arr1.map(val1 => {
    arr2.some(val2 => {
        val2.id === val1.id ? result.push(val2) : result.push(val1)
    })
})
1 Answers

You could do it with this one-liner that uses Array.prototype.reduce

var arr1 = [
    { id: 1, key1: "hello", key2: "world" },
    { id: 2, key1: "some", key2: "value" },
    { id: 3, key1: "...", key2: "..." }
];

var arr2 = [
    { id: 2, key1: "new", key2: "val" },
    { id: 5, key1: "...", key2: "..." }
];

const result = arr1.reduce((acc, cur) => [...acc, arr2.find(({ id }) => cur.id === id) || cur], []);

console.log(result);

Related