0

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

})
R3tep
  • 12,512
  • 10
  • 48
  • 75
  • 1
    `Object.values(x).map` is same as `x.map` for an array. And the inner should be `console.log( Object.values(el).map((el2) => el2.name) )`. OR `x.flatMap(Object.values).map(a => a.name)` will get all the `name`s as an array – adiga Sep 21 '21 at 14:16
  • 1
    Change the console log to ‘ console.log(el.name)’ – CloudBalancing Sep 21 '21 at 14:17
  • `Object.values(x).map((el) => Object.values(el).map((el2) => console.log(el2.name)));` – 0stone0 Sep 21 '21 at 14:17
  • The code is not working it gives me a result [undefined] I'm trying to do Destructuring Parameters But it didn't work –  Sep 21 '21 at 14:20
  • 1
    `map` expects a function that returns something. `(el2) => { el2 }` returns _nothing_ and also does _nothing_. `(el) => { console.log(`…`) }` returns _nothing_; note that `console.log` returns `undefined`. Read the docs: [`=>`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Arrow_functions), [`map`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map). – Sebastian Simon Sep 21 '21 at 14:21

2 Answers2

2

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

R3tep
  • 12,512
  • 10
  • 48
  • 75
0

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

})
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39