1

i have this Object. i want to get the value of "label" dynamically. How do i do this?

var obj = {
  "Admin": true,
     "User": {
        "Someguy": [
          {
            "label": "NG59",
            "Id": 2094602823
          },
          {
            "label": "NG60",
            "Id": 3473631702,
          }
       ]
    }
}

What i've tried:

Object.keys(obj.User)[0] // returns "Someguy"

Object.keys(obj.User)[0][0] // trying to get "label", returns undefined Object.keys(obj.User)[0].label // undefined

How do i access "label" or "Id" dynamically?

David
  • 1,084
  • 12
  • 36

2 Answers2

1

Try this:

var obj = {
  "Admin": true,
  "User": {
    "Someguy": [
      {
        "label": "NG59",
        "Id": 2094602823
      },
      {
        "label": "NG60",
        "Id": 3473631702,
      }
  ]
 }
};

var guy = "Someguy";
var label = Object.values(obj.User[guy][0])[0];
console.log(label);
Faly
  • 13,291
  • 2
  • 19
  • 37
1

You need to take the key for the object to access the inner objects.

var obj = { Admin: true, User: { Someguy: [{ label: "NG59", Id: 2094602823 }, { label: "NG60", Id: 3473631702 }] } },
    key = Object.keys(obj.User)[0];

console.log(key);
console.log(obj.User[key][0].label);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392