Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add value to inner array using map in JavaScript

Suppose I have the following array:

let array = [
  {
    id: "1",
    name: "name",
    categories: [
      {
        subid: "10",
        name: "name",
      },
      {
        subid: "11",
        name: "name",
      }
    ]
  },
  {
    id: "2",
    name: "name",
    categories: [
      {
        subid: "20",
        name: "name",
      },
      {
        subid: "21",
        name: "name",
      }
    ]
  }
]

My goal is to take the id of each of the objects and add it to the inner array categories. So it would look like this:

let array = [
  {
    id: "1",
    name: "name",
    categories: [
      {
        subid: "10",
        name: "name",
        id: "1"
      },
      {
        subid: "11",
        name: "name",
        id: "1"
      }
    ]
  },
  {
    id: "2",
    name: "name",
    categories: [
      {
        subid: "20",
        name: "name",
        id: "2"
      },
      {
        subid: "21",
        name: "name",
        id: "2"
      }
    ]
  }
]

Here is what I have so far:

array.map(x => (x.id)) // returns new array of ids
// add these into the categories

How can I do this using map? If map can't be used I think for each will work as well.

like image 665
cup_of Avatar asked Jan 26 '26 16:01

cup_of


1 Answers

With map method and spread syntax inside object you could do this.

let array = [{"id":"1","name":"name","categories":[{"subid":"10","name":"name"},{"subid":"11","name":"name"}]},{"id":"2","name":"name","categories":[{"subid":"20","name":"name"},{"subid":"21","name":"name"}]}]

let result = array.map(({id, categories, ...rest}) => ({
  ...rest, id, categories: categories.map((o) => ({...o, id}))
}))

console.log(result)
like image 172
Nenad Vracar Avatar answered Jan 29 '26 07:01

Nenad Vracar