簡體   English   中英

如何從 object NodeJS 中提取屬性?

[英]how to extract properties from an object NodeJS?

我在使用 NodeJs 中的 get 請求(使用 express)獲取 object 中的屬性時遇到問題。 我有以下 object:

const amigos = [{
    id: 1,
    nombre: "laura",
    pais: "Inglaterra",
    lenguajes :[ {id: 0, lenguaje:"java"},"python","c++"],
    hobbies : ["leer" , "pescar" , "tenis"]
  },
{
    id: 2,
    nombre: "Rocío",
    pais: "Argentina",
    lenguajes :[ {id: 1, lenguaje:"C++"},"kotlin","GO"],
    hobbies : ["correr" , "Natacion" , "Equitación"]
},
{
    id: 3,
    nombre: "Fede",
    pais: "Argentina",
    lenguajes :[ {id: 2, lenguaje:"PHP"},"python","swift"],
    hobbies : ["Tiro con arco" , "Crossfit" , "Boxeo"]
},
{
    id: 4,
    nombre: "Dany",
    pais: "Colombia",
    lenguajes :[ {id: 3, lenguaje:"java"},"javascript","c++"],
    hobbies : ["Futbol" , "pescar" , "Trekking"]
},
{
    id: 4,
    nombre: "Mariano",
    pais: "Argentina",
    lenguajes :[ {id: 4, lenguaje:"javascript"},"python","java"],
    hobbies : ["Correr" , "Natacion" , "Basketball"]
}]

module.exports = amigos;

我只想提取愛好。

我嘗試了以下方法,但它一直讓我回到整個 object。 不僅是我需要的愛好:

app.get("/amigos", (req, res) => {
    res.status(200);
    // const hobbiesParam = req.params.hobbies; 
//     const response = amigos.map(
//       (a) => { return a.hobbies.toLowerCase()
// });
    res.json(amigos.hobbies);
  });

編輯:預期的 output 應該是一個對象數組,只有每個人的姓名和愛好:

[
  { "nombre": "laura",
    "hobbies": [
      "leer",
      "pescar",
      "tenis"
    ]
  },
  ...
]

只需使用Array.prototype.map()

 const amigos = [{ id: 1, nombre: "laura", pais: "Inglaterra", lenguajes:[ {id: 0, lenguaje:"java"},"python","c++"], hobbies: ["leer", "pescar", "tenis"] }, { id: 2, nombre: "Rocío", pais: "Argentina", lenguajes:[ {id: 1, lenguaje:"C++"},"kotlin","GO"], hobbies: ["correr", "Natacion", "Equitación"] }, { id: 3, nombre: "Fede", pais: "Argentina", lenguajes:[ {id: 2, lenguaje:"PHP"},"python","swift"], hobbies: ["Tiro con arco", "Crossfit", "Boxeo"] }, { id: 4, nombre: "Dany", pais: "Colombia", lenguajes:[ {id: 3, lenguaje:"java"},"javascript","c++"], hobbies: ["Futbol", "pescar", "Trekking"] }, { id: 4, nombre: "Mariano", pais: "Argentina", lenguajes:[ {id: 4, lenguaje:"javascript"},"python","java"], hobbies: ["Correr", "Natacion", "Basketball"] }] console.log( amigos.map( ({ nombre, hobbies }) => ({ nombre, hobbies }) ) );

暫無
暫無

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

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