0

Given an object, say like this:

const data = { 
   "menu":{ 
      "id":"file",
      "value":"File",
      "popup":{ 
         "menuitem":[ 
            { 
               "value":"New",
               "onclick":"CreateNewDoc()"
            },
            { 
               "value":"Open",
               "onclick":"OpenDoc()"
            }
         ]
      }
   }
}

I want to get one of the nested properties of the object, say popup, but that could be the name of any type of Web widget - that's a variable. It seems like either one of these two methods would work, but they both return errors:

    let propName = "popup";

    console.log(data.menu.propName.menuitem);

    console.log(data.menu. + propName + .menuitem);

How do you get the property of an object when one of the property names is a variable?

Andrew Koper
  • 6,481
  • 6
  • 42
  • 50
  • @bergi - it is VERY COMMON in 2019 for web developers to receive data in a complex data structure like this via AJAX and have to parse it to display in a page - this is VERY USEFUL. None of the other questions address this common scenario or hit on Google searches for these words. This question has value. The others are different enough this should not be marked as duplicate. – Andrew Koper Dec 05 '19 at 00:36

3 Answers3

1

Use brackets.

let propName = "popup";

console.log(data.menu[propName].menuitem);

Remember to check it before you try to access it, otherwise it could trigger an error

let propName = "popup";

if(data.menu[propName]){
    console.log(data.menu[propName].menuitem);
}
www-data
  • 244
  • 2
  • 9
-1
let propName = "popup";
const {menu: {[propName]: menuItem}} = data;

And of course, const keyword is always preferable when you don't change your variable's value.

-1

You could also use a ternary operator to handle the variable name, if could be more than one value in your code:

let propName = variableName1 ? variableName1 : variableName2;

console.log(data.menu[`${propName}`].menuitem);
Reena Verma
  • 1,617
  • 2
  • 20
  • 47