forked from bittu1040/JavaScript-Coding-and-Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflatMap.js
More file actions
89 lines (78 loc) · 2.95 KB
/
flatMap.js
File metadata and controls
89 lines (78 loc) · 2.95 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
79
80
81
82
83
84
85
86
87
88
// create an array of objects and inside one key, create an array of objects then inside one key, create an array of objects
const orders = [
{
orderId: 101,
customer: {
name: "Alice"
},
items: [
{
productId: "P001",
productName: "Laptop",
reviews: [{ reviewer: "John", rating: 5 }, { reviewer: "Emily", rating: 4 }]
},
{
productId: "P002",
productName: "Mouse",
reviews: [{ reviewer: "Mark", rating: 4 }, { reviewer: "Anna", rating: 3 }]
}
]
},
{
orderId: 102,
customer: {
name: "Bob"
},
items: [
{
productId: "P003",
productName: "Smartphone",
reviews: [{ reviewer: "Sara", rating: 5 }, { reviewer: "David", rating: 4 }]
},
{
productId: "P004",
productName: "Headphones",
reviews: [{ reviewer: "Alice", rating: 5 }, { reviewer: "Tom", rating: 4 }]
}
]
}
];
//output:
[
{"orderId":101,"customerName":"Alice","productId":"P001","productName":"Laptop","reviewer":"John","rating":5},
{"orderId":101,"customerName":"Alice","productId":"P001","productName":"Laptop","reviewer":"Emily","rating":4},
{"orderId":101,"customerName":"Alice","productId":"P002","productName":"Mouse","reviewer":"Mark","rating":4},
{"orderId":101,"customerName":"Alice","productId":"P002","productName":"Mouse","reviewer":"Anna","rating":3},
{"orderId":102,"customerName":"Bob","productId":"P003","productName":"Smartphone","reviewer":"Sara","rating":5},
{"orderId":102,"customerName":"Bob","productId":"P003","productName":"Smartphone","reviewer":"David","rating":4},
{"orderId":102,"customerName":"Bob","productId":"P004","productName":"Headphones","reviewer":"Alice","rating":5},
{"orderId":102,"customerName":"Bob","productId":"P004","productName":"Headphones","reviewer":"Tom","rating":4}
]
const transformedData = orders.flatMap(order =>
order.items.flatMap(item =>
item.reviews.map(review => ({
orderId: order.orderId,
customerName: order.customer.name,
productId: item.productId,
productName: item.productName,
reviewer: review.reviewer,
rating: review.rating
}))
)
);
const transformedData1 = orders.map(order => {
return order.items.map(item => {
return item.reviews.map(review => {
return {
orderId: order.orderId,
customerName: order.customer.name,
productId: item.productId,
productName: item.productName,
reviewer: review.reviewer,
rating: review.rating
}
})
})
}).flat(Infinity)
console.log(transformedData);
console.log(transformedData1);