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?
let fakeData = { "622b1e4a8c73d4742a66434e212":{ request_id: "1", uique_id:'001' }, "622b1e4a8c73d4742a6643423e54":{ request_id: "1", uique_id:'002' }, "622b1e4a8c73d4742a6643423e23":{ request_id: "2", uique_id:'003' }, } let parts = [] for (const property in fakeData) { console.log(fakeData[property]); } //Result should be // [{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()
.
const fakeData = { "622b1e4a8c73d4742a66434e212": { request_id: "1", uique_id: '001' }, "622b1e4a8c73d4742a6643423e54": { request_id: "1", uique_id: '002' }, "622b1e4a8c73d4742a6643423e23": { request_id: "2", uique_id: '003' }, }, output = Object.values(fakeData).reduce((r, {request_id, uique_id}) => { r[request_id] ??= {request_id, values: []}; r[request_id].values.push(uique_id); return r; },{}), result = Object.values(output); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }