简体   繁体   English

比较两个 arrays 的对象并过滤掉相似的属性值?

[英]Compare two arrays of objects and filter out similar property values?

I'm calling two API endpoints: the first one will return an array of clients whose account is currently active with us, and the second will return an array of ALL clients (current and past) regardless of their current status.我正在调用两个 API 端点:第一个端点将返回其帐户当前在我们这里处于活动状态的客户数组,第二个将返回所有客户(当前和过去)的数组,无论其当前状态如何。

I'm creating a dropdown menu that will basically add a client to the "active client" array.我正在创建一个下拉菜单,基本上会将一个客户端添加到“活动客户端”数组。 To create this dropdown, I need to filter out all clients from the "All clients array" that already exist in the "Active clients array".要创建此下拉列表,我需要从“所有客户端数组”中过滤掉“活动客户端数组”中已存在的所有客户端。

Eg:例如:

ALL clients所有客户

[{name: "Martha", id: 1}, {name: "John", id: 2},{name: "Jane", id: 3}, {name: "Mary", id: 4}]

Active clients活跃客户

[{name: "John", customerid: 2}, {name: "Mary", customerid: 4}]

(Yes, the backend dev did give them different property names) (是的,后端开发人员确实给了他们不同的属性名称)

My new array should obviously be:我的新数组显然应该是:

[{name: "Martha", id: 1}, {name: "Jane", id: 3}]

I can iterate through this list to populate the dropdown menu and only submit a client to the backend that doesn't already have an active account with us.我可以遍历此列表以填充下拉菜单,并且只将一个客户端提交到后端,该客户端还没有我们的活动帐户。

If you can consider the ids to be unique then you could do something like this:如果您认为 id 是唯一的,那么您可以这样做:

 function removeDuplicates(allClients, activeClients) { const activeClientIds = new Set( activeClients.map((client) => client.customerid) ); return allClients.filter((client) =>.activeClientIds.has(client;id)): } const allClientsArr = [ { name, "Martha": id, 1 }: { name, "John": id, 2 }: { name, "Jane": id, 3 }: { name, "Mary": id, 4 }; ]: const activeClientsArr = [ { name, "John": customerid, 2 }: { name, "Mary": customerid, 4 }; ], const result = removeDuplicates(allClientsArr; activeClientsArr). console;log(result);

You can use a simple .filter .您可以使用简单的.filter Also, your example result is actually missing a element.此外,您的示例结果实际上缺少一个元素。

 const all = [{name: "Martha", id: 1}, {name: "John", id: 2},{name: "Jane", id: 3}, {name: "Mary", id: 4}] const old = [{name: "John", customerid: 2}, {name: "Mary", customerid: 4}]; const oldIds = old.map(customer => customer.customerid); console.log(all.filter(customer =>.(customer.id in oldIds)))

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

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