Issue
I’m having issues getting a property inside an object, using get request in NodeJs(with express). I Have the following 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;
And I want to extract only the hobbies.
I have tried the following, but it keeps bringing me back the whole object. Not only the hobbies, which is what I need:
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);
});
Edit: The expected output should be an array of objects just with the name and hobbies per person:
[
{ "nombre": "laura",
"hobbies": [
"leer",
"pescar",
"tenis"
]
},
...
]
Solution
Just use 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 }) ) );