Let's say I have two arrays of objects:
let array1 = [
{
id: 1,
name: 'snow'
},
{
id: 4,
name: 'jo'
},
{
id: 8,
name: 'bran'
},
{
id: 12,
name: 'gondo'
},
{
id: 13,
name: 'peter'
}
]
let array2 = [
{
id: 3,
name: 'brim'
},
{
id: 4,
name: 'not-jo'
},
{
id: 8,
name: 'not-bran'
},
{
id: 13,
name: 'spleen'
}
]
I want to find all the objects in array2 that match by id with array1, and change their name values to match the name values in array1.
In my pseudocode:
array1.forEach((person)=> {
if(person.id is equal to person.id in array2){
person.name = person.name in array1
}
})
Try this :
array2.map(function(x){
var result=array1.filter(a1=> a1.id==x.id);
if(result.length>0) { x.name=result[0].name;}
return x })
Loop through each element and compare there ids. If they match update the name:
for (var i = 0; i < array2.length; i++) {
for (var k = 0; k < array1.length; k++) {
if (array2[i].id == array1[k].id) {
array2[i].name = array1[k].name;
break;
}
}
}
Try it:
let array1 = [{
id: 1,
name: 'snow'
},
{
id: 4,
name: 'jo'
},
{
id: 8,
name: 'bran'
},
{
id: 12,
name: 'gondo'
},
{
id: 13,
name: 'peter'
}
]
let array2 = [{
id: 3,
name: 'brim'
},
{
id: 4,
name: 'not-jo'
},
{
id: 8,
name: 'not-bran'
},
{
id: 13,
name: 'spleen'
}
]
console.log(array2);
for (var i = 0; i < array2.length; i++) {
for (var k = 0; k < array1.length; k++) {
if (array2[i].id == array1[k].id) {
array2[i].name = array1[k].name;
break;
}
}
}
console.log(array2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With