0

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)
2
  • What have you done so far to achieve your goal? Is there a specific issue you're having with your solution? Commented Dec 9, 2021 at 21:02
  • yeah it is related to a different project but once I understand how to solve this, I can implement it into my project Commented Dec 9, 2021 at 21:11

1 Answer 1

1

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 })
})
Sign up to request clarification or add additional context in comments.

2 Comments

Hey was wondering if I wanted to compare another property, could I do it like (value2 => value2.name === value1.name || value2.name === value1.surname)[0].age)
Yes, that will work too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.