Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
27
rated 0 times [  31] [ 4]  / answers: 1 / hits: 16791  / 7 Years ago, fri, july 21, 2017, 12:00:00

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
}
})

More From » javascript

 Answers
26

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 })

[#57013] Tuesday, July 18, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lara

Total Points: 462
Total Questions: 100
Total Answers: 102

Location: Jersey
Member since Mon, Jun 14, 2021
3 Years ago
lara questions
;