【问题标题】:How to read the data from the JSON stringifyed array of objects and loop through it and use the same如何从 JSON 字符串化对象数组中读取数据并遍历它并使用相同的对象
【发布时间】:2020-04-27 08:08:49
【问题描述】:

我正在使用 Node JS 包,下面是我想要的帮助

我有以下 JSON 数据。

[{
"name":"IronMan",
"description":"Genius",
"head_id":"34",
"domain_name":"ironman.com"
}]

我想访问循环内键的值。我不知道如何遍历上面的 JSON 数据。

【问题讨论】:

  • 使用Node?或者干脆JS?

标签: javascript node.js json api


【解决方案1】:
const parsedData= JSON.parse(data) // This will parse your stringifyed Array of objects

parsedData.forEach(entry=> {
// looping through each object in the array and accessing its keys using Object.values()
  Object.values(entry).forEach(value=> {
     console.log(value) // here you will get all the values of all the objects in an d 
  })
})


// You can also use 
Object.keys(entry).forEach(key => {
// key = 'name'
    console.log(entry[key]))
}
// You can also use 
Object.entries(entry).forEach(keyValuePair =>{
 // keyValuePair = ['name', 'IronMan']
  console.log('key', keyValuePair[0])
  console.log('value', keyValuePair[1])
})

【讨论】:

    【解决方案2】:

    然后了解for...in 循环。

    let stuff=[{
    "name":"IronMan",
    "description":"Genius",
    "head_id":"34",
    "domain_name":"ironman.com"
    }];
    
    for(let item of stuff) // this is not the one, just example data is an array
      for(let key in item) // this is the one
        console.log(key,item[key]);

    【讨论】:

    • 谢谢。即使这有助于并产生相同的输出。 :) :D
    猜你喜欢
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 2021-08-15
    相关资源
    最近更新 更多