-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobject.js
More file actions
78 lines (66 loc) · 1.7 KB
/
object.js
File metadata and controls
78 lines (66 loc) · 1.7 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const firstList = [
{
name: 'name1',
place: 'place1',
age: 40,
id: 2
},
{
name: 'name2',
age: 2,
id: 1
}
];
const secondList = [
{
age: 20,
place: 'place3',
id: 2
},
{
place: 'place2',
id: 1
},
{
name: 'name3',
id: 3
}
];
const combineObjectsinArray = (list1, list2) => {
list1.forEach((item, key) => {
list1[key] = {...item, ...list2[key]}
});
return list1;
}
// console.log(combineObjectsinArray(firstList, secondList));
const combineArrayOfObjects = (list1, list2) => {
if (list1.length > list2.length) {
return combineObjectsinArray(list1, list2);
} else {
return combineObjectsinArray(list2, list1);
}
}
// console.log(combineArrayOfObjects(firstList, secondList));
const combineObjectsbyId = (list1, list2) => {
list1.forEach((item1, key) => {
const newListItem = list2.filter(item2 => item1.id === item2.id)[0];
list1[key] = {...item1, ...newListItem}
});
return list1;
}
// console.log(combineObjectsbyId(firstList, secondList));
const combineArrayOfObjectsbyId = (list1, list2, swap = false) => {
if (swap) {
return combineObjectsbyId(list2, list1);
}
return combineObjectsbyId(list1, list2);
}
//console.log(combineArrayOfObjectsbyId(firstList, secondList, true));
const mergedList = combineArrayOfObjectsbyId(firstList, secondList, true);
const sortByKey = (list, key = 'id') => list.sort((a, b) => {
if (a[key] < b[key]) return -1
else if(a[key] > b[key]) return 1
return 0;
});
const byKey = sortByKey(mergedList, 'place');
console.log('\nBy Id', byKey);