【问题标题】:How to parse an array inside an object [closed]如何解析对象内的数组[关闭]
【发布时间】:2021-10-06 08:22:39
【问题描述】:

这是我需要解析的数组,因为我正在解析数组,它在控制台中显示undefined

var jsonString = {
    "results": [{
        "cc_emails": [
            "test@test.com",
            "test1@test.com",
            "tst2@tst2.com"
        ],
        "name": "test",
        "email": "testemail",
        "email_config_id": 14000037621,
        "priority": 2,
        "product_id": null,
        "created_at": "2021-10-05T22:01:17Z",
        "updated_at": "2021-10-05T22:05:05Z"

    }]
}

我需要更正上述错误并显示priority。这是我的代码,它由我用来迭代数组的forEach() 循环组成。

// I used foreach here.
$.each(jsonString, function (index, val) 
{
    alert jsonString[index].priority;  
});

【问题讨论】:

  • 这与 JSON 无关,都是普通的 javascript 对象
  • 另外,alert jsonString[index].priority; 不是有效的 javascript,它应该是 alert (jsonString[index].priority);,您可以将其简化为 alert(val.priority)

标签: javascript arrays object


【解决方案1】:

您的jsonString 是一个包含数组results 的对象。 您需要在结果而不是对象上应用forEach

var jsonString = {
    "results": [{
        "cc_emails": [
            "test@test.com",
            "test1@test.com",
            "tst2@tst2.com"
        ],
        "name": "test",
        "email": "testemail",
        "email_config_id": 14000037621,
        "priority": 2,
        "product_id": null,
        "created_at": "2021-10-05T22:01:17Z",
        "updated_at": "2021-10-05T22:05:05Z"

    }]
}

jsonString.results.forEach(item => {
    console.log(item.priority)
})

【讨论】:

【解决方案2】:

使用现代 javascript,您也可以这样做:

for (const result of jsonString.results) {
  console.log(result.priority);
}

for..of loop documentation

【讨论】:

  • 嗨,我需要通过我的函数返回上面的数组,并且该函数我需要访问另一个 js 文件,所以我该怎么做
【解决方案3】:

你应该在这里使用.results属性

jsonString.results.forEach(result => {
  console.log(result.priority); // prints priority in console
});

如果你需要一个优先级数组,你可以使用

let priorities = jsonString.results.map(result => {
  return result.priority;
});

【讨论】:

  • 使用现代 javascript,您还可以通过使用 for (const result of jsonString.results) 循环来避免回调
  • 嗨,我需要通过我的函数返回上面的数组,并且该函数我需要访问另一个 js 文件,所以我该怎么做
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-29
  • 2012-08-03
相关资源
最近更新 更多