如何根据数组匹配值过滤JSON对象数组并返回新数组?
问题:过滤JavaScript数组中符合条件的对象
原始数据
var structureInfos = [{ name: 'HMDB0006285', identifier: 'Six two eight 5' }, { name: 'HMDB0006288', identifier: 'Six two double eight'}, { name: 'HMDB0006293', identifier: 'Six two nine three' }, { name: 'HMDB0006294', identifier: 'Six two Nine Four' }] var structureElements = [ 'HMDB0006285', 'HMDB0006293', 'HMDB0006294' ]
需求
过滤出structureInfos中name属性值存在于structureElements数组中的对象,预期输出:
[ { name: 'HMDB0006285', identifier: 'Six two eight 5' }, { name: 'HMDB0006293', identifier: 'Six two nine three' }, { name: 'HMDB0006294', identifier: 'Six two Nine Four' } ]
错误代码及问题分析
用户尝试的代码无法正常运行,核心问题有两点:
- 参数名重名:
forEach的回调参数用了和原数组一样的名字structureInfos,导致回调里的structureInfos是单个遍历对象,却错误地用structureInfos[i]['name']去取值 - 逻辑冗余且错误:没必要嵌套循环遍历
structureElements,只需判断当前对象的name是否在目标数组中即可
错误代码:
var newArray = []; structureInfos.forEach(function(structureInfos) { for (let i=0; i < structureElements.length; i++){ if(structureElements[i] === structureInfos[i]['name']){ newArray.push(structureInfos[i]); } } });
正确实现方法
方法1:简洁实现(filter + includes)
利用数组原生的filter方法筛选符合条件的对象,结合includes快速判断归属:
const filteredArray = structureInfos.filter(item => structureElements.includes(item.name)); console.log(filteredArray);
方法2:高性能实现(数据量大时推荐)
如果structureElements数组元素较多,用Set将查找时间复杂度从O(n)降到O(1),提升运行效率:
const elementSet = new Set(structureElements); const filteredArray = structureInfos.filter(item => elementSet.has(item.name)); console.log(filteredArray);
方法3:手动遍历实现(修正原思路)
如果坚持用forEach手动实现,修正参数名和判断逻辑即可:
var newArray = []; structureInfos.forEach(function(item) { if (structureElements.includes(item.name)) { newArray.push(item); } }); console.log(newArray);
内容的提问来源于stack exchange,提问作者user10913305
相关产品推荐
相关产品推荐

