我有以下对象和数字数组。如何判断数组中的哪个数字不作为对象中的 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] Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
对于更多的数据项和更多的
id,我会选择一种创建Set通过mapping 每个itemList项目的id...const idLookup = new Set(itemList.map(({ id }) => id));直接从
集合或Map实例比例如更快通过一次又一次迭代数组查找或包含外部过滤任务。过滤不匹配的 item-
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; }您可以使用
.map(),然后使用.filter()和.includes()const data = [ {id: 60, itemName: 'Main Location - 1100 Superior Road - Cleveland'}, {id: 1456, itemName: 'Third Location - 107,West 20th Street,Manhattan - New York'} ] const ids = [60, 1453, 1456]; const dataIDs = data.map(ob => ob.id); // [60, 1456] const notExistentIDs = ids.filter(id => !dataIDs.includes(id)); console.log(notExistentIDs); // [1453]