【问题标题】:Looping JSON object JavaScript [duplicate]循环 JSON 对象 JavaScript [重复]
【发布时间】:2016-06-22 23:34:45
【问题描述】:

这个 JSON 对象有问题......

{
    "1457458375537": {
        "message": "this is the message",
        "subject": "my subject"
    },
    "1457467436271": {
        "message": "test message",
        "subject": "hello"
    }
}

基本上对于每个对象,所以长号(例如 1457458375537),我想循环但不知道如何引用该长号并循环通过完整的 JSON 对象。

【问题讨论】:

  • Object.keys(JSON.parse(str)) 是一个很好的提示。

标签: javascript arrays json parsing


【解决方案1】:
// data is all the json you gave in the example
for(var key in data){
    // keys are the numbers 
    // and inner are the objects with message and subject
    var inner = data[key]; 
}

【讨论】:

    【解决方案2】:

    长数字是 json 中的键。您可以使用 Object.keys() 函数遍历键:

    var data = {
        '1457458375537': {
            'message': 'this is the message',
            'subject': 'my subject'
        },
        '1457467436271': {
            'message': 'test message',
            'subject': 'hello'
        }
    };
    
    Object.keys(data).forEach(function(key) {
        console.log(key); // prints property name - long number
        console.log(data[key].message);
        console.log(data[key].subject);
    });
    

    【讨论】:

      猜你喜欢
      • 2021-10-30
      • 1970-01-01
      • 2016-07-08
      • 1970-01-01
      • 2019-06-30
      • 2021-05-11
      • 2015-09-16
      • 2018-04-26
      • 2019-11-26
      相关资源
      最近更新 更多