Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting property key from json object

Preamble: I'm Italian, sorry for my bad English.

I need to retrieve the name of the property from a json object using javascript/jquery.

for example, starting from this object:

{
      "Table": {
          "Name": "Chris",
          "Surname": "McDonald"
       }
}

is there a way to get the strings "Name" and "Surname"?

something like:

//not working code, just for example
var jsonobj = eval('(' + previouscode + ')');
var prop = jsonobj.Table[0].getPropertyName();
var prop2 = jsonobj.Table[1].getPropertyName();
return prop + '-' + prop2; // this will return 'Name-Surname'
like image 289
benVG Avatar asked Dec 21 '22 12:12

benVG


1 Answers

var names = [];
for ( var o in jsonobj.Table ) {
  names.push( o ); // the property name
}

In modern browsers:

var names = Object.keys( jsonobj.Table );
like image 116
elclanrs Avatar answered Jan 02 '23 19:01

elclanrs