0

I have this code (which is variant thought the time) in JSON

{
  "5780": {
    "app": "Bye",
    "name": "Hello World",
    "surname": "Friend"
  },
  "6654": {
    "app": "Hello",
    "name": "Hi",
    "surname": "godbye"
  }
}

I want to get the information from each section (for example the "app" section) an insert in a js variable. The problem is that the object title (5780 & 6654) change will change (at the same time, the sections information). So I need something like section[1].app = jsvariable1

Hackerman
  • 12,139
  • 2
  • 34
  • 45
Markel
  • 33
  • 5

2 Answers2

1

You can loop

   var obj = {
      "5780": {
        "app": "Bye",
        "name": "Hello World",
        "surname": "Friend",
      },
      "6654": {
        "app": "Hello",
        "name": "Hi",
        "surname": "godbye",
      }
    }

    for (var key in obj) {
      console.log(obj[key].app);
    }

This will log

Bye
Hello

If you want to update the value of app:

for (var key in obj) {
      obj[key].app = "New Name";
}

The key is the 5780 and 6654

Eddie
  • 26,593
  • 6
  • 36
  • 58
0

First of all, your json is not valid so you have to check it(as i did in the code below) . So here's what i did :

var sections = {
  "5780": {
    "app": "Bye",
    "name": "Hello World",
    "surname": "Friend",
  },

  "6654": {
    "app": "Hello",
    "name": "Hi",
    "surname": "godbye",
  }

};


var index = [];

//setting the index array
for (var x in sections) {
  index.push(x);
}

console.log(sections[index[0]].app)
console.log(sections[index[1]].app)
Neji Soltani
  • 1,522
  • 4
  • 22
  • 41