首页 > 解决方案 > 如何从 JSON Node.js 获取特定的数据值?

问题描述

这是我的 JSON 文件输出:

let employees = [{
  "id":1,
  "name":"Lann",
  "username":"brot",
  "email":"b@sd.com",
  "address": {
    "city":"Gweh",
    "zipcode":"92998-3874",
    "geo": {
      "lat":"45",
      "lng":"77"
    }
  }
}]

我如何从中获取 id、姓名和电子邮件,如下所示:

{
  "id":1,
  "name":"Lann",
  "email":"b@sd.com"
}

标签: javascriptnode.jsjson

解决方案


您可以使用地图存档。

let employees = [{
          "id":1,
          "name":"Lann",
          "username":"brot",
          "email":"b@sd.com",
          "address":{
             "city":"Gweh",
             "zipcode":"92998-3874",
             "geo":{
                "lat":"45",
                "lng":"77"
             }
          }
          }]
const data = employees.map(o => ({ id: o.id, name: o.name, email:o.email }));
console.log(data[0]);


推荐阅读