Retrieve the matching values from a JSON object by filtering it with an array, then create a new JSON object containing only

    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 am attempting to filter out the JSON object with values matching an array and create a new JSON object. However, my current approach is not yielding the expected results.

Expected Output:

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

The following code snippet is not working as intended:

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

Answer №1

If you're looking for a quick and efficient solution, consider using an ES6 arrow function like this:

const filteredArray = structureInfos.filter(info => structureElements.includes(info.name));

Answer №2

Upon reviewing your code, I have identified some errors that may be preventing it from functioning correctly.

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

It seems that you are iterating through the structureElements array within your forEach() loop, but then using the same index identifier "i" when referencing structureInfos. In a forEach function, the first argument in the callback is the current element of the array. To resolve this issue, consider the following revised code:

var newArray = [];
structureInfos.forEach(function(structureInfo) { // Changed the variable name
  for (let i = 0; i < structureElements.length; i++) {
    if (structureElements[i] === structureInfo['name']) { // Removed the index identifier
      newArray.push(structureInfo); // Added explanation for pushing the correct record
    }
  }
});

Answer №3

Method using map and filter

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)

Another approach using filter or includes

  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 newinfo = structureInfos.filter((item)=> structureElements.includes(item.name))
console.log(newinfo)

Approach utilizing loop with spread operator

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 newInfo = [];
for(let item of structureInfos){
  if(structureElements.includes(item.name)){
    newInfo = [...newInfo,item]
  }
}
console.log(newInfo);

Looping method to find matching elements

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 Info = []
for(let stinfo of structureInfos){
    for(let stele of structureElements){
        if(stinfo.name === stele){
          Info.push(stinfo);
          break;
        }
    }
}
console.log(Info)

Using forEach method to match elements

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 newInfo = [];
structureInfos.forEach((element)=>{
  for(let i=0; i<structureElements.length; i++){
    if(element.name === structureElements[i]){
       newInfo.push(element);
       break;
    }
  }
})
console.log(newInfo)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for creating a responsive swiper slider in an Angular project

In my Angular project, I am using a swiper slider with 4 items in desktop view. However, I would like to display only 1 item in the mobile view. You can see the code at this link: https://stackblitz.com/edit/ngx-swiper-wrapper-demo-h9egdh?file=app/app.com ...

Node.js: Configuring keep-alive settings in Express.js

How can I properly implement "keep alive" in an express.js web server? I came across a few examples.. Example 1: var express = require('express'); var app = express(); var server = app.listen(5001); server.on('connection', function(s ...

The Android application encountered an issue where the org.json.simple.JSONObject could not be converted to org.json.JSONObject

My task is to sort scores from a JSONArray and display only the top 10. Below is the code I have written. try { JSONArray jArray = new JSONArray(result); List<String> jsonValues = new ArrayList<String>(); for (int i = 0; i < jArray.length ...

What is the process of integrating passportjs(node) API with the Angular cli?

After successfully configuring Node.js with PassportJS OAuth2, the need arose for Angular to call the Node API. However, they are running on different ports. While calling all of Node.js's REST APIs from Angular works fine using proxy.conf.json, an er ...

Having trouble locating a tag when converting an object to an array in Android using JSONArray

I am currently working on retrieving data from an API using JSON in an Android application. After successfully downloading the information, I need to store it in a JSONArray with the tag "Categories" for display in a ListView. Below is the code snippet I a ...

Moogonse request for modification

json:{ data:{ id:"123"} , res:{ message:false, "resId":"afdsfd" } } I need to make changes to the res field in the JSON above, but I'm having trouble doing it using mongoose in my NodeJS app. Currently, I am attempting t ...

Inject variables into the URL

Having access to an API that provides a list of images, I am presented with 5 parameters as listed below: The first parameter is the keyword for the search (e.g. flowers) The second parameter is size which has a default value The third parameter is orien ...

Guide on incorporating a bootstrap 4 navigation item into an active class through jquery

I am working on a Jekyll site and I want to dynamically add the Bootstrap 4 class active using JavaScript. I have tried using the following code: $(document).ready(function() { // get current URL path and assign 'active' class var pathna ...

Determine the sibling input value using jQuery in an ASP.NET MVC application

In my Asp.net MVC project in Visual Studio 2015, I have a page where I need to update the user's shopping cart with ajax when the quantity of an item is changed. The challenge I'm facing is retrieving the Article Code from another input field in ...

Can you explain the concept of binding and unbinding in jQuery?

Can you explain the concepts of binding and unbinding in jQuery in simple terms for someone who learns slowly? ...

li experiencing a background width problem due to extended text

Check out this code snippet with a problem In the image below, you can see that the background of the li element with more text is larger compared to the others. It's important to note that the <ul> is scrollable. I've experimented with va ...

Vue component using axios for conditional state toggling

My Vue method/function triggers a state change and toggles text on a button upon click. pauseTask: function() { this.isOpen = !this.isOpen; this.pauseButton.text = this.isOpen ? 'Pause' : 'Resume'; }, While it works flawle ...

Send multiple values as arguments to a jQuery function

Beginner question ahead: I'm using the jquery function loadNewPicture() to upload pictures and the progress() function to track the percentage of the upload. Everything is functioning correctly. My query relates to the variables that can be passed t ...

Attempting to develop a filtering feature using ReactJS

Having some trouble with the if statement in my filter list function. Can't seem to figure out why it's not working properly. Here is the code snippet: filterList (event) { var updatedList = this.props.array; var filterText = this.stat ...

Managing user input in Node.js

Users are required to input a URL in the form (e.g: "") and I need to be able to access and read the content from that URL. I am uncertain about my current method. What should I enter in the URL field below? var options = { url: '....', ...

Use ajax calls instead of using the bind() function in Drupal for better performance

Currently, I have an AJAX call that is bound to the window popstate event. While it works fine, the issue arises when parsing arguments from the querystring. The problem lies in the fact that the ajax call gets bound to the window on page load, causing the ...

Encountering the error message: ERESOLVE unable to solve dependency tree while trying to install

I'm encountering an error when attempting to install a dependency. How can I resolve this issue? npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" cla ...

What is the best way to analyze a JSON dataframe in order to determine the frequency of names that are identified as both male and female?

I am struggling with creating a query that filters an existing dataframe to display the count of names that are shared by both males and females. We defined a name as female if the number of women and men were equal. I need help writing a filter for the d ...

Exporting Data Using Excel and a Javascript Table

Currently, I am utilizing angularjs to export data into excel from an uploaded table. Here is the code snippet I am using: function (e) {<br> window.open('data:application/vnd.ms-excel,' + encodeURIComponent($('div[id$=exporta ...

Encountering some difficulties while setting up my development tool (specifically webpack)

I have embarked on a journey to learn modern JavaScript with the help of Webpack and Babel. As a beginner in this field, my instructor is guiding me through the principles of modern JavaScript by building an app called Forkify - a recipe application. While ...