确定对象和数组中的值之间的差异
P粉930534280
P粉930534280 2023-09-03 19:28:50
0
2
469
<p>我有以下对象和数字数组。如何判断数组中的哪个数字不作为对象中的 id 存在?在下面的示例中,我想要 1453。</p> <pre class="brush:php;toolbar:false;">[ {id: 60, itemName: 'Main Location - 1100 Superior Road - Cleveland'} {id: 1456, itemName: 'Third Location - 107,West 20th Street,Manhattan - New York'} ] [60, 1453, 1456]</pre></p>
P粉930534280
P粉930534280

全部回复(2)
P粉420868294

对于更多的数据项和更多的id,我会选择一种创建Set 通过 mapping 每个 itemList项目的id...

const idLookup = new Set(itemList.map(({ id }) => id));

直接从集合Map 实例比例如更快通过 一次又一次迭代数组查找 包含外部过滤任务。

过滤不匹配的 item-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; }
P粉130097898

您可以使用 .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]
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!