forked from rohan-paul/Awesome-JavaScript-Interviews
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpush-nested-array-of-objects-to-another.js
56 lines (45 loc) · 1.21 KB
/
push-nested-array-of-objects-to-another.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Interview question faced on 14-July-2018- at Thrymer Software, Hyderabad
// myProjectsArr is an array of objects, within which I also have the property 'employee' which is also an array of objects.
// Write a function to push 2 employees to each of the project with myProjectsArr
var myProjectsArr = [{
projId: '1',
projName: 'A',
employee: []
},
{
projId: '2',
projName: 'B',
employee: []
}
]
var myEmployeeArr = [{
employeeId: 1,
employeeName: 'abc'
},
{
employeeId: 2,
employeeName: 'cde'
},
{
employeeId: 3,
employeeName: 'abc'
},
{
employeeId: 4,
employeeName: 'cde'
}
]
console.log(myProjectsArr[0].employee);
console.log(myProjectsArr[1].employee);
// Generic function to add the nested array (which is itself an array of objects ) to the outer projectsArr ( which is and arr of objects )
addEmployee = (projectsArr, employeesArr ) => {
for (let i in projectsArr) {
let nestedEmployeeArr = projectsArr[i].employee;
nestedEmployeeArr.push(employeesArr.splice(0, 2))
}
return projectsArr;
}
// Execute the function on my set of data
addEmployee(myProjectsArr, myEmployeeArr);
console.log(myProjectsArr[0].employee);
console.log(myProjectsArr[1].employee);