crawlings
crawlings

Reputation: 61

Filter two arrays with nested objects with Javascript

My use case: I have a two arrays one called "name" and the other called "customer". I need to extract the customers from the names list and get a new array called "lead".

const name = [{
  id: 1,
  name: "smith"
}, {
  id: 2,
  name: "john"
}]

const customer = [{
  id: 1,
  name: {
    id: 1,
    name: "smith"
  }
}]

I am expecting to get

lead = [{
  id: 2,
  name: "john"
}]

the code I am using is

const name = [{
  id: 1,
  name: "smith"
}, {
  id: 2,
  name: "john"
}]

const customer = [{
  id: 1 a,
  name: {
    id: 1,
    name: "smith"
  }
}]


const lead = name.filter(({
  id: id1
}) => !customer.some(({
  "name.id": id2
}) => id2 === id1));
console.log(lead);

This works if the data is flat, but when I use it with nested objects I get the full "name" list.

Working final code below

While Farrukh Normuradov answer does work, I used Pilchard's answer in the comments. I also fixed a typo.

Final code

const lead = name.filter(({ id: id1 }) => !customer.some(({ name: {id: id2} }) => id2 === id1));

Upvotes: 1

Views: 66

Answers (1)

Farrukh Normuradov
Farrukh Normuradov

Reputation: 1184

I used filter, map and includes.

const user_list = [{
    id: 1,
    name: "smith"
}, {
    id: 2,
    name: "john"
},
{
    id: 3,
    name: "timur"
},
{
    id: 4,
    name: "igor"
},]

const customers = [{
    id: 1,
    name: {
        id: 1,
        name: "smith"
    }
},
{
    id: 4,
    name: {
        id: 4,
        name: "igor"
    }
}]

const leads = user_list.filter(user => !customers.map(customer => customer.id).includes(user.id))

console.log(leads);

Upvotes: 2

Related Questions