Home > Mobile >  How to get the value of the Name of an element inside a JSON object?
How to get the value of the Name of an element inside a JSON object?

Time:03-18

I have the following object:

var list = {
    "to do": {
    key: 99, 
    important: ["example1", "example2"], 
    others: ["example3", "example4"]
    }
};

I want to understand how I can extract the value to do from list.

I want to log the value to a variable: var x = "to do"

I tried to locate it, but to do does not seem to have an index. list[0] // undefined.

Does anyone have a simple solution how to do this ?

CodePudding user response:

Use Object.keys() to get the keys of list. Since you only have one key use [0] If you have more than one key solution may differ

var list = {
    "to do": {
    key: 99, 
    important: ["example1", "example2"], 
    others: ["example3", "example4"]
    }
};
let x=Object.keys(list)[0];
console.log(x)

CodePudding user response:

First, extract data from the list variable followed by your key string.

   var list = {
        "to do": {
        key: 99, 
        important: ["example1", "example2"], 
        others: ["example3", "example4"]
        }
    };
    var x=list["to do"];
    console.log(x)
  • Related