Home > Software design >  Converting Array of object to another array of objects
Converting Array of object to another array of objects

Time:12-06

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

[
{ TaskID: "1001", TaskName: "task1", AID: "10"},
{ TaskID: "1002", TaskName: "task2", AID: "10"}
]
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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
  },
 
]
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

CodePudding user response:

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.

CodePudding user response:

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);
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related