-1

I have an array of objects like in the following structure.

[
{ TaskID: "1001", TaskName: "task1", AID: "10"},
{ TaskID: "1002", TaskName: "task2", AID: "10"}
]

I have to create an array from the above array to the following structure.

[
  {
    "TaskID": 1,
    "Value": "1001",
    "AID": 10
  },
   {
    "TaskID": 2,
    "Value": "task1",
    "AID": 10
  },
   {
    "TaskID": 1,
    "Value": "1002",
    "AID": 10
  },
 {
    "TaskID": 2,
    "Value": "task2",
    "AID": 10
  },
 
]

I've succeeded by using this below code but not sure it is the best method.

let taskIdArray = this.taskArray.map((tasks) => {
                return {
                    TaskID: 1,
                    Value: tasks.tID,
                    AId: tasks.AID
                }
            })          

            let taskNameArray = this.taskArray.map((tasks) => {
                return {
                    TaskID: 2,
                    Value: tasks.Name,
                    AId: tasks.AID
                }
            })
            
            this.finalTaskArray =  taskIdArray.concat(taskNameArray);

Can anyone help me to optimize the code and suggest a better method if any?

sarasm
  • 305
  • 1
  • 6
  • 16
  • Your expected output does not match you input, you are mixing `tID` with `TaskID`, and `Name` with `TaskName`. The code you show puts all elements with TaskID 1 before the elements with TaskID 2, but in your expected output, the IDs are alternating. – GOTO 0 Dec 05 '21 at 19:18

2 Answers2

0

You could also use the index that gets passed to the map callback:

this.finalTaskArray = [].concat.apply([], this.taskArray.map((task, index) => [
  {
    TaskID: index + 1,
    Value: task.TaskID,
    AId: task.AID
  },
  {
    TaskID: index + 2,
    Value: task.Name,
    AId: task.AID
  }
]));

I have also used [].concat.apply([], arrayOfArrays) to flatten the structure as you need. I got the inspiration from this answer.

Octavian Mărculescu
  • 4,312
  • 1
  • 16
  • 29
0

Array#reduce is another way to get there.

let tasks = [
{ TaskID: "1001", TaskName: "task1", AID: "10"},
{ TaskID: "1002", TaskName: "task2", AID: "10"}
]

let newtasks = tasks.reduce( (b,a) => [...b, {TaskID:1, Value: a.TaskID, AID: a.AID}, {TaskID:2, Value: a.TaskName, AID: a.AID}],[])
console.log(newtasks);
Kinglish
  • 23,358
  • 3
  • 22
  • 43