First question here (I mean like ever), so sorry if I posted at the wrong section or haven't found an already given answer.
I have 2 arrays of objects. The first one, lets call it oldArray has 1000 objects with attributes
{id, name, age, address, favourite number, favourite mathematician}.
The other one, lets call it inputArray has 20 objects which attributes are a subset of the objects in oldArray, for example
{id, age, favourite number}.
What I need is to create an updatedArray, lets call it newArray in which the objects from the oldArray which IDs aren't in the inputArray stay unaltered, but the attributes of the objects which IDs exist in the inputArray are overwritten by the new ones.
I have made it work with fors and ifs but I am searching for
a) a more efficent way
b) a "cleaner" way, like using lodash or something I don't know :P
c) preferably both of the above
So expected results.
let oldArray=[
{
id:1,
name:Akis,
age: 27,
address: Mykonos,
favourite number: 23,
favourite mathematician: Riemann
},
{
id: 2,
name: Mary,
age: 41,
address: Paros,
favourite number: 10,
favourite mathematician: Ramanujan
},
{
id: 3,
name: Sofia,
age: 13,
address: Ithaka,
favourite number: 4,
favourite mathematician: Gauss
},
{
id:4,
name: Anthony,
age: 18,
address: Koufonisia,
favourite number: 33,
favourite mathematician: Metallica
},
{
id:5,
name:Yolo,
age: 99,
address: Somewhere,
favourite number: 123,
favourite mathematician: Euler
}
]
///////////////////////////////////////////////////////
let inputArray = [
{
id: 2,
age: 23,
favourite number: 13
},
{
id:5,
age: 100,
favourite number: 99
}
]
\\\\\\\\\\\\\\\\\\\\\\\\\\\\
let newArray = [
{
id:1,
name:Akis,
age: 27,
address: Mykonos,
favourite number: 23,
favourite mathematician: Riemann
},
{
id: 2,
name: Mary,
age: 23,_________________________________// !CHANGED!
address: Paros,
favourite number: 13,____________________// !CHANGED!
favourite mathematician: Ramanujan
},
{
id: 3,
name: Sofia,
age: 13,
address: Ithaka,
favourite number: 4,
favourite mathematician: Gauss
},
{
id:4,
name: Anthony,
age: 18,
address: Koufonisia,
favourite number: 33,
favourite mathematician: Metallica
},
{
id:5,
name:Yolo,
age: 100,_________________________________// !CHANGED!
address: Somewhere,
favourite number: 99,_____________________// !CHANGED!
favourite mathematician: Euler
}
]
PS. I am missing some quotes but i Hope you get the point! :P
newArraysupposed to contain completely distinct objects fromoldArray(i.e., copies of them)? I'd probably save the new array as an objectnkeyed byid, and then do anoldArray.map(i => Object.assign({}, i, n[i.id]))