Home > Mobile >  Map through an object with children objects/array
Map through an object with children objects/array

Time:11-25

I am trying to map through an arraycategory(which is inside an object List) and access id and name which are inside an array of objects.

Below is my data.

List = {
    category: [
      {
        id: 1,
        name: 'Alpha',
      },
      {
        id: 2,
        name: 'Bravo',
      },
      {
        id: 3,
        name: 'Charlie',
      },
    ],
  }

Below is react code that is trying to access id and name.

{List.category.map((index, res) => {
                console.log("Output:",res)
              })}

//Output: 0
//Output: 1
//Output: 2
//Output: 0
//Output: 1
//Output: 2
...

How can I access name and id that are inside category?

Please let me know your suggestions.

CodePudding user response:

This will work. (Although you shouldn't be using map if you don't want to render actual output in the UI - but I assume this is just debugging code.)

{List.category.map(({ name, id }) => {
  console.log("Output:", name, id);
})}
  • Related