Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading