Converting javascript array data into an object

Viewed 31

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, ...}

1 Answers

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!

Related