簡體   English   中英

如何從 JSON Node.js 獲取特定數據值?

[英]How to get particular data values from JSON Node.js?

這是我的 JSON 文件 output:

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

我如何從下面獲得 id、name 和 email:

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

您可以使用 map 存檔。

 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]);

如果您的數組只有一個元素,您可以只訪問信息,無需像這樣構建另一個數組: employees[0].id , employees[0].name , employees[0].email或者您可以提取一個 object使用 Object 解構

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

但是如果你的陣列有更多的員工,我認為你需要做的是通過 id 或 name 搜索並返回一個 object 並提供最少的信息,你可以這樣做

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

您可以通過使用數組解構來簡單地做到這一點。

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

// Destructuring array
const [employee] = employees;

** 現在從這里開始, employee是 object,您可以像訪問其他對象一樣正常訪問其屬性。 用於獲取idnameusername :**

employee.id;
employee.name;
employee.username;

如果它包含多個項目,您還可以循環通過您的輸入並獲得一組收縮項目:

 let employees = [{ "id": 1, "name": "Lann", "username": "brot", "email": "b@sd.com", "address": { "city": "Gweh", "zipcode": "92998-3874", "geo": { "lat": "45", "lng": "77" } } }] let shrink = []; for (let employee of employees) { shrink.push({ id: employee.id, name: employee.name, email: employee.email }); } console.log(shrink);

如果“lat”:存在並且如果存在返回員工ID值,如何搜索嵌套值geo?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM