Search code examples
javascriptarraysecmascript-6ecmascript-5

Convert nested aray into group of objects: Javacript


I am having an object that has the following structure

const arr = [
  {field: "f1", values: [{ count:1, value: "a"}, { count:2, value: "b"}] },
  {field: "f2", values: [{ count:3, value: "c"}, { count:4, value: "d"}] }
];

Output should look like

output = {
  f1: { name: "f1", selected: [] },
  f2: { name: "f2", selected: [] }
}

Basically the value in field should be key in the new object, also its name should have the same value with empty selected array

Code that I tried.

arr.map(item => {
    return { item: { name: item, selected: [] } }
  }
);

Solution

  • const arr = [
        { field: "f1", values: [{ count: 1, value: "a" }, { count: 2, value: "b" }] },
        { field: "f2", values: [{ count: 3, value: "c" }, { count: 4, value: "d" }] }
    ]
    
    const output = arr.reduce((p, { field }) => {
        p[field] = { name: field, selected: [] };
        return p;
    }, {});
    
    console.log(output);