【问题标题】:how to extract properties from an object NodeJS?如何从对象 NodeJS 中提取属性?
【发布时间】:2021-03-03 16:09:27
【问题描述】:

我在使用 NodeJs 中的 get 请求(使用 express)获取对象内部的属性时遇到问题。我有以下对象:

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;

我只想提取兴趣爱好。

我尝试了以下方法,但它不断将我带回整个对象。不只是爱好,这是我需要的:

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

编辑:预期的输出应该是一个对象数组,只有每个人的姓名和爱好:

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

【问题讨论】:

    标签: javascript node.js express object


    【解决方案1】:

    只需使用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 }) ) );

    【讨论】:

      猜你喜欢
      • 2021-06-17
      • 2015-02-21
      • 1970-01-01
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-10
      相关资源
      最近更新 更多