我有以下对象和数字数组。如何判断数组中的哪个数字不作为对象中的 id 存在?在下面的示例中,我想要 1453。
[
{id: 60, itemName: 'Main Location - 1100 Superior Road - Cleveland'}
{id: 1456, itemName: 'Third Location - 107,West 20th Street,Manhattan - New York'}
]
[60, 1453, 1456]
对于更大数量的数据项和更大数量的id
我会选择一种方法来创建Set https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set基于查找通过map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/mapping 每个itemList
item's id
...
const idLookup = new Set(itemList.map(({ id }) => id));
直接从 a 查找项目Set
or a Map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map实例比例如快得多通过一次又一次迭代数组find https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find or includes https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes对于外部的每个迭代步骤filter https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter task.
过滤不匹配项目的列表 -id
那么就很简单...
const listOfNonMatchingIds = idList.filter(id => !idLookup.has(id));
...示例代码...
const itemList = [
{ id: 60, itemName: 'Main Location - 1100 Superior Road - Cleveland' },
{ id: 1456, itemName: 'Third Location - 107,West 20th Street,Manhattan - New York' },
];
const idList = [60, 1453, 1456];
const idLookup = new Set(itemList.map(({ id }) => id));
const listOfNonMatchingIds = idList.filter(id => !idLookup.has(id));
console.log({ listOfNonMatchingIds });
.as-console-wrapper { min-height: 100%!important; top: 0; }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)