I have this kind of data, my goal is to find all same request_id
values in the given objects, merge it to one object and append its unique_id
into one array, How can I get this result?
JavaScript
x
24
24
1
let fakeData = {
2
"622b1e4a8c73d4742a66434e212":{
3
request_id: "1",
4
uique_id:'001'
5
},
6
"622b1e4a8c73d4742a6643423e54":{
7
request_id: "1",
8
uique_id:'002'
9
},
10
"622b1e4a8c73d4742a6643423e23":{
11
request_id: "2",
12
uique_id:'003'
13
},
14
}
15
16
let parts = []
17
18
for (const property in fakeData) {
19
console.log(fakeData[property]);
20
}
21
22
23
//Result should be
24
// [{request_id:'1', values:["001, 002"]}, {request_id:'2', values:["003"]}]
Advertisement
Answer
You can iterate over all the values using Object.values()
and array#reduce
. In the array#reduce
group based on request_id
in an object and extract all the values of these object using Object.values()
.
JavaScript
1
8
1
const fakeData = { "622b1e4a8c73d4742a66434e212": { request_id: "1", uique_id: '001' }, "622b1e4a8c73d4742a6643423e54": { request_id: "1", uique_id: '002' }, "622b1e4a8c73d4742a6643423e23": { request_id: "2", uique_id: '003' }, },
2
output = Object.values(fakeData).reduce((r, {request_id, uique_id}) => {
3
r[request_id] ??= {request_id, values: []};
4
r[request_id].values.push(uique_id);
5
return r;
6
},{}),
7
result = Object.values(output);
8
console.log(result);
JavaScript
1
1
1
.as-console-wrapper { max-height: 100% !important; top: 0; }