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' ]
I want to filter out the json object with values matching with an array and return a new json object. I tried the below, but does not seem to work.
Expected Output:
Expected : [
{ name: 'HMDB0006285', identifier: 'Six two eight 5' },
{ name: 'HMDB0006293', identifier: 'Six two nine three' },
{ name: 'HMDB0006294', identifier: 'Six two Nine Four' }
]
Below Code doesnt seem to work:
var newArray = [];
structureInfos.forEach(function(structureInfos) {
for (let i=0; i < structureElements.length; i++){
if(structureElements[i] === structureInfos[i]['name']){
newArray.push(structureInfos[i]);
}
}
});
3
Answers
1st Method using map or filter
2nd Method filter or includes
3rd Method loop or spread operator
4th method using loops
5th method using foeach
I see some errors in your code that probably explain why it isn’t working for you.
It looks like you are iterating through your structureElements array inside your forEach(), but then you are using the same index identifier "i" when referencing structureInfos. With the forEach function the first argument in the callback is the current element of the array, so this should work better for you:
Here is a simple one liner solution using ES6 arrow function: