javascript - 使用 json 从特定键中检索每个值

标签 javascript json

我想知道是否有办法从 .json 中获取“-temp”的每个值

{
  "weather":{
    "notes":{
      "cities":[
        {
          "-id":"scranton",
          "-temp":"17"
        },
        {
          "-id":"paris",
          "-temp":"16"
        },
        {
          "-id":"new york",
          "-temp":"18"
        }
      ]
    }
  }
}

我是如何尝试用 JavaScript 获取它的,但没有成功,我得到了 undefined

data.weather.notes.cities['-temp']

如何获取“-temp”的每个值?

最佳答案

您可以使用 map :

const temps = data.weather.notes.cities.map(city => city["-temp"]);

console.log(temps); // ["17", "16", "18"]

当然,您始终可以单独访问它们:

const { cities } = data.weather.notes;

console.log(cities[0]["-temp"]); // "17"

或者循环所有的:

for (let city of cities) {
  console.log("temperature in %s is %s°", 
    city["-id"], city["-temp"]
  );
}

关于javascript - 使用 json 从特定键中检索每个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58858331/

相关文章:

json - Amazon AWS CLI 不允许在有效负载参数中使用有效的 JSON

java - JSONException 尝试从 JSON 获取值

javascript - 如何使用 javascript 处理此布局?

javascript语法错误设置jquery数据表的属性

javascript - 将输入类型时间转换为 firestore 的时间戳

javascript - CRM 2011 - 动态更改表单问题 - JS 错误(无法执行代码...)

javascript - 使用await函数循环抛出错误

javascript - 来自 ajax 的 Bootstrap 表 json

c# - JSON 字符串上的字符串 'Input string was not in a correct format' 异常

json - 如何在 PySpark 中保存从 URL 获取的 JSON 数据?