Skip to content Skip to sidebar Skip to footer

How To Loop Through An Array With Pure Javascript

I have an empty dropdown list that is dependent on the value from another dropdown. I want to write it with vanilla JS not Jquery that will populate the dropdown with the sample da

Solution 1:

There are many different ways you could do this using pure javascript.

Once you receive your array of data from your GET request, you could use a for loop to iterate through the data and create one big html string (htmlToInsert) of each <option> with the relevant data inside.


Object.entries() returns an array whose elements are arrays corresponding to the enumerable string-keyed property [key, value] pairs found directly upon object.

Then you can use array destructuring assignment to get the key and value pair.

Once you have that, you can simply insert it with Element.insertAdjacentHTML()


Note: for performance reasons, it is best practice to batch all your DOM changes at once, instead of changing the DOM inside a loop.

const data = [{"1":"ABA NORTH"},{"2":"ABA SOUTH"},{"3":"AROCHUKWU"},{"4":"BENDE"},{"5":"IKWUANO"},{"6":"ISIALA NGWA NORTH"},{"7":"ISIALA NGWA SOUTH"},{"8":"ISUIKWUATO"},{"9":"OBINGWA"},{"10":"OHAFIA"},{"11":"OSISIOMA"},{"12":"UGWUNAGBO"},{"13":"UKWA EAST"},{"14":"UKWA WEST"},{"15":"UMUAHIA NORTH"},{"16":"UMUAHIA SOUTH"},{"17":"UMU - NNEOCHI"}]


let htmlToInsert = ''for (let i = 0; i < data.length; i++) {
  const [[key, val]] = Object.entries(data[i])
  htmlToInsert += `<option value="${key}">${val}</option>`
}


const select = document.querySelector('#profileapplicationform-lga_id')
select.insertAdjacentHTML('beforeend', htmlToInsert)
<selectname="states"id="profileapplicationform-lga_id"><optionvalue="">Select one</option></select>

Solution 2:

Look at this line:

html+= '<option value="' +data[i][0]+ '">' +data[i][1]+ '</option>';

You can't get items from objects by index, but you can do

data[key] //returns value

So your code should go about like this

html+= '<option value="' +Object.keys(data[i])[0]+ '">' +data[i][Object.keys(data[i])]+ '</option>';

Object.keys(data[i])[0] first gets the keys of data[i]. There is only one key, so simply get the first element of the returned array. That is your key.

data[i][Object.keys(data[i])] gets an element. It then takes advantage of the data[key] property to get the value of that element.

And, instead of using list.append(), you can try using list.innerHTML += html

Solution 3:

I see better your example data and in this case, you need to use Object.entries in order to get the key and the value of every object:

const data = [{"1":"ABA NORTH"},{"2":"ABA SOUTH"},{"3":"AROCHUKWU"},{"4":"BENDE"},{"5":"IKWUANO"},{"6":"ISIALA NGWA NORTH"},{"7":"ISIALA NGWA SOUTH"},{"8":"ISUIKWUATO"},{"9":"OBINGWA"},{"10":"OHAFIA"},{"11":"OSISIOMA"},{"12":"UGWUNAGBO"},{"13":"UKWA EAST"},{"14":"UKWA WEST"},{"15":"UMUAHIA NORTH"},{"16":"UMUAHIA SOUTH"},{"17":"UMU - NNEOCHI"}]


data.forEach(item => {
  for (let [key, value] ofObject.entries(item)) {
    html += `<option value="${key}">${value}</option>`;
  }
});

Solution 4:

something like that ? (pure JS code)

window.onload =()=>
  {
  const select     = document.getElementById("profileapplicationform-state_origin_id")
    ,   selectList = document.getElementById("profileapplicationform-lga_id")
    ;
  select.oninput =()=>
    {
    selectList.innerHTML = '<option value="">Select one</option>'
      ;
    fetch ( baseurl,  // ??
      {
      method: 'POST',
      headers: newHeaders(),
      body:JSON.stringify({state_origin_id: select.value})
      })
    .then ( resp => resp.json())
    .then ( data =>
      {
      data.forEach(elm=>
        {
        let [key, val] = Object.entries(elm)[0]
        selectList.add(newOption(val,key))
        })
      })
    .catch ( err =>console.log(err) )
    }
  }

Javascript fetch -> https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

javascript new Option -> https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptionElement/Option

more question(s)?

Solution 5:

The Fetch API can be used instead of the jQuery $.ajax() method.

PHASES

  1. GET your JSON (POSTed the exact JSON provided in question to a live test server)

  2. Iterate through the JSON to access each Object within the Array

  3. On each Object, convert it into an array and destructure it to access both key and value

  4. Render an htmlString of an <option> for each key/value pair to the target <select>


DEMO

Note: The <form>, the attribute event onchange=... assigned to the <form>, and the <output> are not required. They are added for demonstration purposes.

const dataToSelect = async(endpoint, selector = "select") => {
  const select = document.querySelector(selector);
  const response = awaitfetch(endpoint);
  let data = await response.json();

  for (let object of data) {
    for (let [key, value] ofObject.entries(object)) {
      let optionHTML = `<option value='${key}'>${value}</option>`;
      select.insertAdjacentHTML('beforeend', optionHTML);
    }
  }
  return data;
}

dataToSelect('https://api.myjson.com/bins/1h3cbk', '#pick');
:root,
body {
  font: 4003vw/1.5 Verdana
}

select,
option,
output {
  font: inherit;
  display: inline-block;
  width: 20ch;
}
<formid='main'onchange='view.value = pick.value; return false'><selectid='pick'name='pick'><optionvalue=''default>PICK A LOCATION</option></select><labelfor='view'>VALUE: </label><outputid='view'for='pick'></output></form>

Post a Comment for "How To Loop Through An Array With Pure Javascript"