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

Converting javascript array data into an object

convert this type of data

const data = [
  { name: 'hcs_utils', starCount: 0 },
  { name: 'K', starCount: 0 },
  { name: 'Heroes of Wesnoth', starCount: 0 },
  { name: 'Leiningen', starCount: 1 },
  { name: 'TearDownWalls', starCount: 1 }]

into this kind of object {"K":5, "Leiningen":4, …}

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

>Solution :

const data = [
  { name: "hcs_utils", starCount: 0 },
  { name: "K", starCount: 0 },
  { name: "Heroes of Wesnoth", starCount: 0 },
  { name: "Leiningen", starCount: 1 },
  { name: "TearDownWalls", starCount: 1 },
];

/* 
    // desired format
    {
        "hcs_utils": 0,
        "K": 0,
        // so on 
    }

*/

const formattedDataArray = data.map((each) => {
  const { name, starCount } = each;
  return {
    [name.toString()]: starCount,
  };
});

console.log("formattedDataArray is", formattedDataArray);

// with reduce

const resultWithReduce = formattedDataArray.reduce((prev, current) => {
  return {
    ...prev,
    ...current,
  };
}, {});

console.log("resultWithReduce is", resultWithReduce);

// without reduce

let resutlWithoutReduce = {};

formattedDataArray.forEach((eachElement) => {
  const key = Object.keys(eachElement)[0];
  const value = Object.values(eachElement)[0];
  resutlWithoutReduce[key] = value;
});

console.log("resultWithoutReduce is", resutlWithoutReduce);

Hope it helps!

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