javascript 使用数组过滤json对象,并返回一个新的json,其值与数组匹配

polkgigr  于 2023-04-19  发布在  Java
关注(0)|答案(1)|浏览(212)
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' ]

我想过滤掉值与数组匹配的JSON对象,并返回一个新的JSON对象。我尝试了下面的方法,但似乎不起作用。
预期输出:

Expected : [
  { name: 'HMDB0006285', identifier: 'Six two eight 5' },
  { name: 'HMDB0006293', identifier: 'Six two nine three' },
  { name: 'HMDB0006294', identifier: 'Six two Nine Four' }
]

下面的代码似乎不起作用:

var newArray = [];
structureInfos.forEach(function(structureInfos) {
   for (let i=0; i < structureElements.length; i++){
        if(structureElements[i] === structureInfos[i]['name']){
           newArray.push(structureInfos[i]);
        }
   }
});
hs1ihplo

hs1ihplo1#

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' ]
    
let newStructureInfos =     structureElements.map((ele)=>{
return structureInfos.filter((item)=>item.name === ele)
}).flat();
console.log(newStructureInfos)

相关问题