Reputation: 515
I have the solution for the problem but is their any better approach to do this
var arr1 = [
{
name: 'Ajinkya',
job: 'Engineer 3',
tasks: ['task1', 'task2', 'task3']
},
{
name: 'Vidhya',
job: 'Engineer 1',
tasks: ['task1', 'task2']
},
{
name: 'Saravana',
job: 'Engineer 2',
tasks: ['task2', 'task3']
},
]
var arr2=[];
arr1.map(e1=>{
e1['tasks'].forEach(e2=>{
arr2.push({ name: e1["name"], job: e1["name"], tasks: e2 })
})
})
console.log(arr2);
Just wanted to iterate the array like the above output, even have a solution, but just wondering about a better approach.
Upvotes: 1
Views: 73
Reputation: 36584
You can use flatMap()
and use map()
over the tasks
for each object
var arr1 = [
{
name: 'Ajinkya',
job: 'Engineer 3',
tasks: ['task1', 'task2', 'task3']
},
{
name: 'Vidhya',
job: 'Engineer 1',
tasks: ['task1', 'task2']
},
{
name: 'Saravana',
job: 'Engineer 2',
tasks: ['task2', 'task3']
},
]
const res = arr1.flatMap(x => x.tasks.map(tasks => ({...x, tasks})));
console.log(res)
Upvotes: 4