-2

I want to create an array of objects inside I want to create one more array of objecrs from an array of objects.

I want array of object to be like this

[
    {
      id: "1",
      tasks: [
        {
          id: "12ef-3902",
          title: "Title 1",
          start: "2022-06-01"
          end: "2022-09-02"
        },
      ],
    },
    {
      id: "2",
      tasks: [
        {
          id: "12ef-3904",
          title: "Title 2",
          start: "2022-02-01",
          end: "2022-04-02"
        },
      ],
    },
    {
      id: "3",
      tasks: [
        {
          id: "12ef-3906",
          title: "Title 3",
          start: "2022-10-09",
          end: "2022-12-02"
        },
      ],
    }
  ];

And this is my current array of objects

[
  {
    id:"1",
    productId:"12ef-3902",
    productName:"title 1",
    startDate:"2022-06-01",
    endDate:"2022-09-02"
   },
   {
     id:"2",
    productId:"12ef-3904",
    productName:"title 2",
    startDate:"2022-02-01",
    endDate:"2022-04-02"
   },
   {
     id:"3",
    productId:"12ef-3906",
    productName:"title 3",
    startDate:"2022-10-09",
    endDate:"2022-12-02"
   }
]

Here is my code I am not sure how to get array of object inside tasks.

  var arr2 = listData.map((v) => ({
    id: v.id,
  }));
  • Does this answer your question? [Elegant way to transform certain property names in an array map](https://stackoverflow.com/questions/53108575/elegant-way-to-transform-certain-property-names-in-an-array-map) – pilchard Apr 26 '22 at 08:08

1 Answers1

2

You can use map to process your array, using object destructuring to simplify the code:

listData = [{
    id: "1",
    productId: "12ef-3902",
    productName: "title 1",
    startDate: "2022-06-01",
    endDate: "2022-09-02"
  },
  {
    id: "2",
    productId: "12ef-3904",
    productName: "title 2",
    startDate: "2022-02-01",
    endDate: "2022-04-02"
  },
  {
    id: "3",
    productId: "12ef-3906",
    productName: "title 3",
    startDate: "2022-10-09",
    endDate: "2022-12-02"
  }
];

result = listData.map(({ id, productId, productName, startDate, endDate}) => ({
  id,
  tasks : [{ id : productId, title: productName, start: startDate, end: endDate }]
})
)

console.log(result)
Nick
  • 138,499
  • 22
  • 57
  • 95