I am trying to compare 2 objects by their property and the values. If the value of the "name" property matches up with each other, I want to push the property and value to value3.
Once value3 is logged, I want the response like this:
{
name: 'dog',
surname: 'good',
skills: 'programming',
age: '22'
},
{
name: 'cat',
surname: 'soft',
skills: 'engineer'
age: '12'
},
{
name: 'elephant',
surname: 'big',
skills: 'programming'
age: '23'
}
Here is the code:
var values1 = [
{
name: 'dog',
surname: 'good',
skills: 'programming'
},
{
name: 'cat',
surname: 'soft',
skills: 'engineer'
},
{
name: 'elephant',
surname: 'big',
skills: 'programming'
}
]
var values2 = [
{
name: 'cat',
food: 'fish',
age: '12'
},
{
name: 'elephant',
food: 'leafs',
age: '13'
},
{
name: 'dog',
food: 'treats',
age: '22'
}
]
// push into this empty object array
var values3 = [{}]
console.log(values3)
CodePudding user response:
const values1 = [
{ name: 'dog', surname: 'good', skills: 'programming' },
{ name: 'cat', surname: 'soft', skills: 'engineer' },
{ name: 'elephant', surname: 'big', skills: 'programming' }
]
const values2 = [
{ name: 'cat', food: 'fish', age: '12' },
{ name: 'elephant', food: 'leafs', age: '13' },
{ name: 'dog', food: 'treats', age: '22' }
]
const values3 = values1.map((value1) => {
return Object.assign(value1, { age: values2.filter(value2 => value2.name === value1.name)[0].age })
})
console.log(values3)
The code above will only work if for each name in values1 an object with name exists in values2. If not use this code:
const values3 = values1.map((value1) => {
const found = values2.find(value2 => value2.name === value1.name)
return Object.assign(value1, { age: found ? found.age : undefined })
})