Skip to content Skip to sidebar Skip to footer

Javascript - Using For (key In Json) - I Would Like To Get Every Other Key Note Json Consists Only Of Objects

I would like to use for (key in json) but only use every other key. It would be simple using arrays, but the json I recieve consists only of objects. I have already asked a smilila

Solution 1:

Solved.

The credit goes to @Ashwin.

He reworked the code a little bit and now it works.

loadJSON(function(json) {
  console.log("json start");
  var i = 0;
  var l = Object.keys(json).length;
  for (x in json){
    console.log(i);
    if (i % 2 === 0){
      data1.innerHTML+="<img src=" + json[x].picture + "/>";
      data1.innerHTML+=json[x].price_thingy.price + json[x].price_thingy.suf;
      console.log("0 " + l);
    } else {
      data2.innerHTML+="<img src=" + json[x].picture + "/>";
      data2.innerHTML+=json[x].price_thingy.price + json[x].price_thingy.suf;
      console.log("1 " + l);
    }
    i++;
  }
});

Solution 2:

You are looping throught the entire json again. If I understand right you want only values of the json object with key l[i].

let json = 
  {
    "123":{
      "name":"someName",
      "age":"12",
      "health":{
        "heart":"OK",
        "lungs":"Not so good"
      }
    },
    "223": {
      "name":"someName1",
      "age":"42",
      "health":{
        "heart":"Not so good",
        "lungs":"OK"
      }
    }
  }

let l = Object.keys(json)
console.log(l.length)

for(let i = 0; i < l.length; i++){
  let element = json[l[i]];
  console.log(`id=${i}, ${element.name}, ${element.health.lungs}`);
}

Here is my example :

https://jsbin.com/yavosiroxi/edit?js,console

Post a Comment for "Javascript - Using For (key In Json) - I Would Like To Get Every Other Key Note Json Consists Only Of Objects"