gpt4 book ai didi

javascript - 从列表中删除列表 - 逻辑

转载 作者:行者123 更新时间:2023-11-28 17:06:59 26 4
gpt4 key购买 nike

我有 2 个列表对象,需要从 ListA 中删除包含 ListB 的所有项目并返回剩余的项目。我的方法如下:

列表A

[{
"id": 1,
"name": "ant"
}, {
"id": 2,
"name": "ant2"
}, {
"id": 3,
"name": "ant3"
}, {
"id": 4,
"name": "ant3"
}, {
"id": 5,
"name": "ant3"
}]

列表B

[{
"id": 1,
"name": "ant"
}, {
"id": 4,
"name": "ant4"
}, {
"id": 3,
"name": "ant3"
} ]

我尝试过的:

const xxx = this.listA.filter(x => !listB.includes(x) != null);

注意(替代场景):当有 2 个相同的 List 时,预期结果是 []。但是,就我而言,它与单个列表相同。

最佳答案

给你:)

const listBSerialized = listB.map(x => JSON.stringify(x)) 
const xxx = listA.filter(x => !listBSerialized.includes(JSON.stringify(x)));

您将得到以下结果:

[ { id: 2, name: 'ant2' },
{ id: 4, name: 'ant3' },
{ id: 5, name: 'ant3' } ]

您还可以在序列化时需要属性顺序保证时使用模型,有时对象可以具有相同的属性但顺序不同(这取决于对象来自哪里):

function Ant(id, name) {
this.id = id
this.name = name
}

listA = [
new Ant(1, "ant"),
new Ant(2, "ant2"),
new Ant(3, "ant3"),
new Ant(4, "ant3"),
new Ant(5, "ant3")
]

listB = [
new Ant(1, "ant"),
new Ant(4, "ant4"),
new Ant(3, "ant3")
]

const listBSerialized = listB.map(x => JSON.stringify(x))
const xxx = listA.filter(x => !listBSerialized.includes(JSON.stringify(x)));

关于javascript - 从列表中删除列表 - 逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55622914/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com