I am working with multiple array elements and I need to merge them into a single element.
Below are the array elements:
[
{"2627":{"pid":"2619","level":"2","mid":"2627","name":"EXCEPTION HOURS","children":[]}},
{"2626":{"pid":"2619","level":"2","mid":"2626","name":"AVAIL TIME","children":[]}},
{"3058":{"pid":"2619","level":"2","mid":"3058","name":"WORK CENTER","children":[]}},
{"3057":{"pid":"2619","level":"2","mid":"3057","name":"CENTRAL OFFICE","children":[]}},
{"2605":{"pid":"2619","level":"2","mid":"2605","name":"IDLING","children":[]}},
{"2607":{"pid":"2619","level":"2","mid":"2607","name":"COMPLIANT RETURN %","children":[]}},
{"2608":{"pid":"2619","level":"2","mid":"2608","name":"COMPLIANT DEPART %","children":[]}}
]
Once combined, the output should appear as follows:
{
"2627":{"pid":"2619","level":"2","mid":"2627","name":"EXCEPTION HOURS","children":[]},
"2626":{"pid":"2619","level":"2","mid":"2626","name":"AVAIL TIME","children":[]},
"3058":{"pid":"2619","level":"2","mid":"3058","name":"WORK CENTER","children":[]},
"3057":{"pid":"2619","level":"2","mid":"3057","name":"CENTRAL OFFICE","children":[]},
"2605":{"pid":"2619","level":"2","mid":"2605","name":"IDLING","children":[]},
"2607":{"pid":"2619","level":"2","mid":"2607","name":"COMPLIANT RETURN","children":[]},
"2608":{"pid":"2619","level":"2","mid":"2608","name":"COMPLIANT DEPART","children":[]}
}
Despite using the array reduce code shown below, it is not functioning correctly:
const output = input.reduce((a, obj) => {
a[obj.mid] = obj;
return a;
}, {});
console.log(output);
const input = [
{"2627":{"pid":"2619","level":"2","mid":"2627","name":"EXCEPTION HOURS","children":[]}},
{"2626":{"pid":"2619","level":"2","mid":"2626","name":"AVAIL TIME","children":[]}},
{"3058":{"pid":"2619","level":"2","mid":"3058","name":"WORK CENTER","children":[]}},
{"3057":{"pid":"2619","level":"2","mid":"3057","name":"CENTRAL OFFICE","children":[]}},
{"2605":{"pid":"2619","level":"2","mid":"2605","name":"IDLING","children":[]}},
{"2607":{"pid":"2619","level":"2","mid":"2607","name":"COMPLIANT RETURN %","children":[]}},
{"2608":{"pid":"2619","level":"2","mid":"2608","name":"COMPLIANT DEPART %","children":[]}}
]
const output = input.reduce((a, obj) => {
a[obj.mid] = obj;
return a;
}, {});
console.log(output);