【问题标题】:Retrieve values from json object从 json 对象中检索值
【发布时间】:2016-01-09 18:32:41
【问题描述】:

我有一个 JSON 对象,其结构如下...

 [{"staffId":4,"forename":"Testf","surname":"Tests","location":"Testl","phoneNumber":"00000000000","email":"Teste"}]

谁能告诉我如何检索键和值并添加到 JavaScript 或 JQuery 中的数组。例如...

var headings = ["staffId","forename","surname"];
var staff = [["1","Joe","Bloggs"],["2","Stack","Overflow"]];

【问题讨论】:

  • 你的旧json里的员工信息在哪里?
  • 在上面的第一个例子中。
  • 在上面的第一个示例中,1 Joe Bloggs 在哪里?
  • 好吧,也许我不够清楚。所以我想要员工 = [["4","Test","Test"]]

标签: javascript json gson


【解决方案1】:

对于一个这样的 JSON 对象,它将是

var json =  [{"staffId":4,"forename":"Testf","surname":"Tests","location":"Testl","phoneNumber":"00000000000","email":"Teste"}];

var headings = Object.keys(json[0]);
var staff = [];
for ( var key in json[0] )
{
   staff.push( json[0][ key ] );
}
console.log( headings );
console.log( staff );

对于多个,你需要像迭代它们一样

for ( var counter = 0; counter < json.length; counter++ )
{
  var jsonObj = json[ counter ];
  //same code for all json objects as above
}

【讨论】:

  • 还有一件事......你知道我如何将员工添加到员工数组中的单独数组中吗?例如[[数组[5]],[数组[5]]
【解决方案2】:

如果我理解正确,你想做这样的事情:

var data = [
    {
        'staffId': 1,
        'forename': 'Joe',
        'surname': 'Bloggs',
        'location': 'Testl1',
        'phoneNumber': '0770....',
        'email': 'Teste1'
    },
    {
        'staffId': 4,
        'forename': 'Testf',
        'surname': 'Tests',
        'location': 'Testl',
        'phoneNumber': '07702671940',
        'email': 'Teste'
    }
];

var headings = ["staffId","forename","surname"];

var result = data.map(function(item) {
    return headings.map(function(heading) {
        return item[heading];
    });
});

console.log(result);

您可以使用Array.prototype.map() 映射/转换您的数组。

【讨论】:

    【解决方案3】:

    你可以用jQuery解析Json

    var json = $.parseJSON(data);
    

    调用值

    alert(json.name);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-01
      • 2021-11-09
      相关资源
      最近更新 更多