Wasteland
Wasteland

Reputation: 5399

JS - merge 2 arrays based on properties

I'm trying to merge 2 arrays of objects where the resulting array should have only objects present in array 1 (selectedNames) but with one property from corresponding objects from array 2 (nameDetails). There's one matching (unique) property to match them:

const selectedNames = [
  {
    id: '11'
    name: 'joe',
  },
  {
    id: '22',
    name: 'bill',
  },
];

const nameDetails = [
  {
    nameId: '11',
    salary: '23422',
    location: 'New Jersey',
  },
  {
    nameId: '33',
    salary: '23424',
    location: 'New York',
  },
  {
    nameId: '22',
    salary: '99999',
    location: 'Boston',
  },
  { nameId: '44',
    salary: '323232',
    location: 'Chicago',
  },
];

The matching property is selectedNames.id === nameDetails.nameId. All entries in selectedNames will definitely be present in nameDetails (but not the other way round). The resulting array should look like that:

[
  {
    id: '11',
    name: 'joe',
    salary: '23422',
  },
  {
    id: '22',
    name: 'bill',
    salary: '99999'
  }
]

I'm a bit confused. I know it'll probably consist of .includes() and filter() and ... for merging? I'm not sure how to handle it.

Alternatively, which will probably be much easier, filter the nameDetails array to have only objects with nameId that exists (as id) in selectedNames.

Upvotes: 0

Views: 90

Answers (2)

user13952187
user13952187

Reputation:

Maybe this fits your needs:

selectedNames.map(({ id, name }) => {
    let salary = nameDetails.find((nameItem) => nameItem.nameId === id).salary;
    return { id, name, salary };
})

Will result in:

[
  {
    id: '11',
    name: 'joe',
    salary: '23422',
  },
  {
    id: '22',
    name: 'bill',
    salary: '99999',
  }
]

Upvotes: 1

Đinh Carabus
Đinh Carabus

Reputation: 3494

I am a bit confused by your example result. For example where does id: '11111' come from?

Are you looking for something like this maybe?

const selectedNames = [
  {
    id: '11',
    name: 'joe',
  },
  {
    id: '22',
    name: 'bill',
  },
];

const nameDetails = [
  {
    nameId: '11',
    salary: '23422',
    location: 'New Jersey',
  },
  {
    nameId: '33',
    salary: '23424',
    location: 'New York',
  },
  {
    nameId: '22',
    salary: '99999',
    location: 'Boston',
  },
  { nameId: '44',
    salary: '323232',
    location: 'Chicago',
  },
];

const merged = selectedNames.map(n => {
  n.salary = nameDetails.filter(d => n.id === d.nameId)[0].salary;
  return n;
});

console.log(merged)

Note: This will change the original selectedNames by adding the salary from the corresponding entry in nameDetails.

Upvotes: 2

Related Questions