简体   繁体   English

用嵌套对象过滤两个 arrays 和 Javascript

[英]Filter two arrays with nested objects with Javascript

My use case: I have a two arrays one called "name" and the other called "customer".我的用例:我有两个 arrays 一个称为“名称”,另一个称为“客户”。 I need to extract the customers from the names list and get a new array called "lead".我需要从名称列表中提取客户并获得一个名为“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.虽然 Farrukh Normuradov 的回答确实有效,但我在评论中使用了 Pilchard 的回答。 I also fixed a typo.我还修正了一个错字。

Final code最终代码

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

I used filter , map and includes .我使用了filter mapincludes .

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM