Javascript 从json对象获取属性键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13912142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:06:43  来源:igfitidea点击:

Getting property key from json object

javascriptjqueryjsonobjectproperties

提问by benVG

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.

我需要使用 javascript/jquery 从 json 对象中检索属性的名称。

for example, starting from this object:

例如,从这个对象开始:

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

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

有没有办法获得字符串“Name”和“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'

回答by elclanrs

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

In modern browsers:

在现代浏览器中:

var names = Object.keys( jsonobj.Table );

回答by Julien Royer

You can browse the properties of the object:

您可以浏览对象的属性:

var table = jsonobj.Table;
for (var prop in table) {
  if (table.hasOwnProperty(prop)) {
    alert(prop);
  }
}

The hasOwnPropertytest is necessary to avoid including properties inherited from the prototype chain.

hasOwnProperty测试对于避免包含从原型链继承的属性是必要的。

回答by Jai

In jquery you can fetch it like this:

在 jquery 中,您可以像这样获取它:

$.ajax({
    url:'path to your json',
    type:'post',
    dataType:'json',
    success:function(data){
      $.each(data.Table, function(i, data){
        console.log(data.name);
      });
    }
});