I am studying Javascript and trying to make the Map function print only the name. I try to do that but I did not succeed. I hope to find a solution for you. Thank you
const x = [{
a: {
name: "X",
age: "25"
},
b: {
name: "Y",
age: "30"
}
}]
Object.values(x).map((el) => {
console.log(Object.values(el).map((el2) => {
el2
}))
})
You don't return any values in your second map.
Return the name and it's would work :
const x = [{
a: {
name: "X",
age: "25"
},
b: {
name: "Y",
age: "30"
}
}]
x.forEach((el) => {
console.log(Object.values(el).map(({ name }) => name))
})
Note: replace your first map by forEach, is more appropriate
.map() is to map the data into a new array.
You need .forEach().
Since you have an array of objects. And each object has multiple keys, you can use Object.keys() for the inner objects.
const x = [{
a: {
name: "X",
age: "25"
},
b: {
name: "Y",
age: "30"
}
}]
x.forEach((el) => {
let keys = Object.keys(el);
//console.log(keys);
keys.forEach((innerKey) => {
console.log(el[innerKey].name);
});
})