gpt4 book ai didi

javascript - 查找仅包含不同对象的数组

转载 作者:行者123 更新时间:2023-11-28 17:02:34 25 4
gpt4 key购买 nike

我有一个数组:

var objArray = [
{ id: 0, name: ‘Object 0’, otherProp: ‘321’ },
{ id: 1, name: ‘O1’, otherProp: ‘648’ },
{ id: 2, name: ‘Another Object’, otherProp: ‘850’ },
{ id: 3, name: ‘Almost There’, otherProp: ‘046’ },
{ id: 4, name: ‘Last Obj’, otherProp: ‘984’ },
{ id: 0, name: ‘Object 0’, otherProp: ‘321’ }
];

此处 id 0 添加两次。我只想要一个不具有相同对象的数组。

预期输出:

a = [
{ id: 0, name: ‘Object 0’, otherProp: ‘321’ },
{ id: 1, name: ‘O1’, otherProp: ‘648’ },
{ id: 2, name: ‘Another Object’, otherProp: ‘850’ },
{ id: 3, name: ‘Almost There’, otherProp: ‘046’ },
{ id: 4, name: ‘Last Obj’, otherProp: ‘984’ }]

如何在 JavaScript 中执行此操作。

最佳答案

您可以通过在 Set 中查找 id 来过滤数组。

var array = [{ id: 0, name: 'Object 0', otherProp: '321' }, { id: 1, name: 'O1', otherProp: '648' }, { id: 2, name: 'Another Object', otherProp: '850' }, { id: 3, name: 'Almost There', otherProp: '046' }, { id: 4, name: 'Last Obj', otherProp: '984' }, { id: 0, name: 'Object 0', otherProp: '321' }],
seen = new Set,
result = array.filter(({ id }) => !seen.has(id) && seen.add(id));

console.log(result);

关于javascript - 查找仅包含不同对象的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56933597/

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