0

How can I iterate trough a json with random keys? For example:

{
  "-KI4TtMlcCgy489krrRK" : {
    "name" : "apple",
    "text" : "green"
  },
  "-KI4TycSzSXwSviWQf5C" : {
    "name" : "banana",
    "text" : "yellow"
  },
  "-KI4U11GePHK9IdeROt7" : {
    "name" : "carrot",
    "text" : orange"
  }
}

I am trying to return:

  • apple - green

  • banana - yellow

  • carrot - orange

CyberJunkie
  • 21,596
  • 59
  • 148
  • 215

1 Answers1

1

You can just do a for in loop. Then you get the key and can do whatever you want to.

var data = {
  "-KI4TtMlcCgy489krrRK" : {
    "name" : "apple",
    "text" : "green"
  },
  "-KI4TycSzSXwSviWQf5C" : {
    "name" : "banana",
    "text" : "yellow"
  },
  "-KI4U11GePHK9IdeROt7" : {
    "name" : "carrot",
    "text" : "orange"
  }
};

for( var key in data ) {
    if( data.hasOwnProperty(key) ) {
        console.log(key);
        console.log(" - " + data[key].name + " - "+ data[key].text);
    }
}
eisbehr
  • 12,243
  • 7
  • 38
  • 63