I have parsed an object into JSON. When I use the console log, it shows like this.
{14: "Cromwell"}
How can I get the key value from it.
I have parsed an object into JSON. When I use the console log, it shows like this.
{14: "Cromwell"}
How can I get the key value from it.
Use a for loop to split each key-value pair, like this:
var data = {1:'a', 2:'b', 3:'c'};
for(var key in data){
console.log('key = ' + key + ', value = ' + data[key]);
}
Let's say your variable is named "myObj", so you'll have:
const myObj = {14:"Cromwell"};
To access the key, you can use the Object.keys method:
const myKey = Object.keys(myObject).pop();
This will return you "14" as a result, which is a string equivalent of the key you're trying to obtain. To convert it to an integer, just use the parseInt() method.
To get the value from that object, then you can do:
const myValue = myObject[myKey];