gpt4 book ai didi

javascript - 从 Java 脚本中的数组列表中排除 ID 列表

转载 作者:行者123 更新时间:2023-11-28 12:19:30 25 4
gpt4 key购买 nike

我有两个数组,其中一个包含我想要从员工数组中删除的 ID 列表。

在 Java 脚本中执行此操作的最佳方法是什么?我可以使用任何 ES6 语法

{
"excludeIDArray": [
1,
3,
4
]
}



{
"employee": [
{
"id": "1",
"name": "joe"
},
{
"id": "2",
"name": "john"
},
{
"id": "3",
"name": "mike"
},
{
"id": "4",
"name": "alex"
},
{
"id": "5",
"name": "sean"
}
]
}

我希望输出是一个看起来像这样的数组

{
"employee": [
{
"id": "2",
"name": "john"
},
{
"id": "5",
"name": "sean"
}
]
}

最佳答案

只需使用 Array.prototype.filterArray.prototype.indexOfparseInt(用于将字符串 ID 转换为数字)。

const exc = {"excludeIDArray":[1,3,4]}
const inObj = {"employee":[{"id":"1","name":"joe"},{"id":"2","name":"john"},{"id":"3","name":"mike"},{"id":"4","name":"alex"},{"id":"5","name":"sean"}]}

const outObj = {
employee: inObj.employee.filter(e => exc.excludeIDArray.indexOf(parseInt(e.id, 10)) === -1)
}

console.log(outObj);

<小时/>

您还可以使用Array.prototype.includes (如果可用)而不是 Array.prototype.indexOf 因为它肯定更具可读性

e => !exc.excludeIDArray.includes(parseInt(e.id, 10))
<小时/>

另一个选项是将排除数组转换为 Set这将带来更好的 (O(1)) 性能

const exc = {"excludeIDArray":[1,3,4]}
const inObj = {"employee":[{"id":"1","name":"joe"},{"id":"2","name":"john"},{"id":"3","name":"mike"},{"id":"4","name":"alex"},{"id":"5","name":"sean"}]}

const exclude = new Set(exc.excludeIDArray)
const outObj = {
employee: inObj.employee.filter(e => !exclude.has(parseInt(e.id, 10)))
}
console.info(outObj)

关于javascript - 从 Java 脚本中的数组列表中排除 ID 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41670213/

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