Best method for extracting object values from an array in Javascript using loops?

Recently Updated: Complete values of respons:

"{"versions":[  
   {  
      "name":"Windows 8.1 with Update 3 (build 9600)",
      "version_id":"11"
   },
   {  
      "name":"Windows 7 SP1 (build 7601)",
      "version_id":"9"
   },
   {  
      "name":"Windows 10, Version 1803 - Redstone 4 [Apr 2018] (build 17134.1)",
      "version_id":"97"
   },
   {  
      "name":"Windows 10, Version 1709 - Redstone 3 [Sep 2017] (build 16299.15)",
      "version_id":"92"
   },
   {  
      "name":"Windows 10, Version 1703 - Redstone 2 [March 2017] (build 15063.0)",
      "version_id":"41"
   },
   {  
      "name":"Windows 10, Version 1607 - Redstone 1 [Jul 2016] (build 14393.0)",
      "version_id":"16"
   },
   {  
      "name":"Windows 10, Version 1511 - Threshold 2 [Nov 2015] (build 10586.0)",
      "version_id":"13"
   },
   {  
      "name":"Windows 10, Version 1511 - Threshold 2 [Feb 2016] (build 10586.104)",
      "version_id":"14"
   },
   {  
      "name":"Windows 10, Version 1511 - Threshold 2 [Apr 2016] (build 10586.164)",
      "version_id":"15"
   },
   {  
      "name":"Windows 10, Version 1507 - Threshold 1 [Jul 2015] (build 10240.16384)",
      "version_id":"12"
   }
]
}"

An array in the following format has been provided:

{
   "versions":[
      {
         "name":"Windows 8.1 with Update 3 (build 9600)",
         "version_id":"11"
      },
      {
         "name":"Windows 7 SP1 (build 7601)",
         "version_id":"9"
      },
      {
         "name":"Windows 10, Version 1803 - Redstone 4 [Apr 2018] (build 17134.1)",
         "version_id":"97"
      }
   ]
}

The goal is to extract name and version_id for adding them to a select dropdown list. The desired outcome should look like this:

  success: function(response){
    var options = ''; 

    $(response.versions).each(function() {
        options += '<option value="' + $(this).attr('version_id') + '">' + $(this).attr('name') + '</option>';
    });

https://i.sstatic.net/kJFOM.png

However, there seems to be an issue in retrieving version_id and name. Is there any alternative method to achieve this?

Answer №1

Avoid using jQuery in this scenario - simply loop through the versions property. It is recommended to set attributes and text content directly instead of inserting text that will be parsed as HTML:

const input = {
  "versions": [{
      "name": "Windows 8.1 with Update 3 (build 9600)",
      "version_id": "11"
    },
    {
      "name": "Windows 7 SP1 (build 7601)",
      "version_id": "9"
    },
    {
      "name": "Windows 10, Version 1803 - Redstone 4 [Apr 2018] (build 17134.1)",
      "version_id": "97"
    }
  ]
};
const select = document.querySelector('select');
input.versions.forEach(({ name, version_id }) => {
  const option = select.appendChild(document.createElement('option'));
  option.value = version_id;
  option.textContent = name;
});
<select>
</select>

Answer №2

A simple method to populate a select tag in HTML is to iterate through an array and dynamically add options using jQuery.

var data = {
   "versions":[
      {
         "name":"Windows 8.1 with Update 3 (build 9600)",
         "version_id":"11"
      },
      {
         "name":"Windows 7 SP1 (build 7601)",
         "version_id":"9"
      },
      {
         "name":"Windows 10, Version 1803 - Redstone 4 [Apr 2018] (build 17134.1)",
         "version_id":"97"
      }
   ]
};

data.versions.forEach(function(e){

  $("#sel").append(`<option value="${e.version_id}">${e.name}</option>`)


})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="sel"></select>

Answer №3

Avoid using $() and remember that attr() serves the purpose of reading attributes from an HTML element

In this case, this represents the object, so simply utilize object notation to access its properties

 $.each(response.versions, function() {
        options += '<option value="' + this.version_id + '">' + this.name + '</option>';
 });

Answer №4

Just like others have mentioned, there is no need for jQuery in this case. It's worth noting that jQuery may not be the best option for working with JSON data since it is primarily designed for XML/DOM elements.

Instead, you can use a simple ES6 approach that utilizes map and reduce:

response.versions.map(v => `<option value="${v.version_id}">${v.name}</option>`).reduce((acc, opt) => acc + opt)

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

Simplified jQuery function for multiple div mouseover operations

Uncertain about the accuracy of my title. Due to certain reasons, I need to assign different IDs for the class, as it only detects ID and not class when hovered over. Therefore, I have created a CSS version where the opacity of a specific div will change t ...

Explaining the process of defining `this.props` and storing data in the global Redux state

I am currently diving into the world of react and Redux and I'm using a react project on GitHub called overcode/rovercode-ui as a learning tool for understanding react and Redux. As I explore this project, I have come across some intriguing questions. ...

The where clause in the Typeorm query builder instance is not functioning properly after its common usage

When fetching data for my relations, I opted to use QueryBuilder. In order to validate certain get request parameters before the index, I established a common QueryBuilder instance as shown below. // Common Get Query const result = await this.reserva ...

What is the most effective method to avoid duplicating elements in the DOM tree?

Seeking a solution for appending a span element to the DOM. if (check something...) { const newSpan = createElement('span'); newSpan.id = '_span'; const container = document.getElementById('container'); conta ...

How to retrieve the input value in React Autosuggest

I recently began my journey into learning JavaScript and React. Currently, I am working on creating a simple table with material design. The goal is to be able to add rows to the table through a form popup and delete rows using an icon within each row. On ...

What is the reason for Jquery AJAX appending additional path to the relative path?

I am encountering an issue with the following code snippet $.ajax({ url: "search/prefetch", success: function (data) { $(".result").html(data); alert("Load was performed."); }, dataType: "json" } ...

Encountering an issue while attempting to replicate the Spotify app on localhost:3000. The error message "TYPEERROR: Cannot read property 'url' of undefined" is hind

As a first-time user of stackoverflow, I am unfamiliar with its rules and regulations, so I apologize in advance for any mistakes I may make. Currently, I am attempting to create a Spotify clone using React. Everything was going smoothly until I completed ...

Generating HTML content from XML data with the help of JavaScript

Challenge: Attempting to display one question and its four corresponding answers at a time from an XML file. JavaScript code: var xmlDoc, quest, ans, i, n; xmlDoc = loadXMLDoc("questions.xml"); quest = xmlDoc.getElementsByTagName('main'); do ...

Display WordPress post content within a specific div element

My Wordpress site has a unique homepage design featuring a div on the left showcasing the titles of the five most recent posts. Adjacent to that is an empty div on the right with a scroll bar. I am in search of a solution whereby clicking on any post tit ...

Node.js application experiences a crash upon entering incorrect credentials

Would you mind reviewing my Login Function? After entering incorrect credentials, a response is sent but unfortunately the app crashes The versions I am using are Express ^4.17.2 and Node.js v16.14.0 router.post( "/login", [ body(" ...

Tips for avoiding html entities in a string

To prevent any user-entered content from being interpreted as HTML, I need to escape it so that special characters like < become < in the markup. However, I still want to wrap the escaped content with actual HTML tags. The goal is to ensure that the ...

AngularJS faces issue with view not reflecting changes made to model

A web-based game I am developing lets players bid on cards and trade them with one another. The technology stack for this application includes Node, Express, MongoDB, and Angular. The player avatars and names, along with their connection status, are displ ...

Challenge with the submission event listener

I am struggling to create my first event listener for the submit button that should respond to both a click and an enter key press. Currently, it is not working for either event, and I am unsure why. I do not intend to send any data to another page; I simp ...

Retrieve the text content from the HTML document

I'm facing a beginner's challenge. I have a div element and I want to extract the URL from the data-element attribute into a .json file Is there a way to do this? <div content="" id="preview" data-element="http://thereislink" class="sample ...

Submitting a form with AJAX using JQuery in ASP.Net is made even easier when utilizing Master Pages for

After developing a search program with lucene.net, I encountered an issue where reloading the entire page was necessary to submit a new query. To resolve this, I explored implementing AJAX for seamless search submission, but have been facing difficulties i ...

Help needed with PHP, MYSQL, and AJAX! Trying to figure out how to update a form dynamically without triggering a page refresh. Can anyone

Hey there! I'm fairly new to the world of dynamically updating databases without needing a page refresh. My goal is to build something similar to The end result I'm aiming for includes: Dynamically generating fields (Done) Loading existing dat ...

Sign up a new user using Passport JS

Looking to utilize passport.js for adding a new user from the signup page. The signup form is as follows: <form id="Signup-form" name="SignupForm" action="/signup" method="post"/> <input type="text" id="firstname" name="Firstname" > <input ...

Running Python in React using the latest versions of Pyodide results in a malfunction

As someone who is new to React and Pyodide, I am exploring ways to incorporate OpenCV functionality into my code. Currently, I have a working piece of code that allows me to use numpy for calculations. However, Pyodide v0.18.1 does not support OpenCV. Fort ...

Storing information in a database using serialization and PHP

In my project, I am using the serialize method to transfer data from one page to another via AJAX. Here is how I do it: var txtCoursesNamewith = $('#with').serialize(); On the PHP page, I retrieve the data like this: $txtCoursesNamewith = ($_P ...

extract all elements from an array nested within another array

I am having difficulty extracting data from an array file in PHP. I was able to read it and convert it into a PHP array, but now I want to display the stored information in a table, however, I keep getting incorrect values. How can I retrieve the informat ...