Skip to content
Advertisement

How to convert json object keys into different arrays removing the duplicate

I’m having the JSON like this i need to group this JSON with all the keys in JSON object and value should in array (excluding duplicates).

var people = [
    {sex:"Male", name:"Jeff"},
    {sex:"Female", name:"Megan"},
    {sex:"Male", name:"Taylor"},
    {sex:"Female", name:"Madison"}
];

My output should be like

{"sex":["Male","Female"],"name":["Jeff","Megan","Taylor","Madison"]}

how we can able to achieve this

Advertisement

Answer

You could use the Array.reduce() method to transform your array into a single object:

var people = [
    {sex:"Male", name:"Jeff"},
    {sex:"Female", name:"Megan"},
    {sex:"Male", name:"Taylor"},
    {sex:"Female", name:"Madison"}
];

const transformed = people.reduce((acc, e) => {
  Object.keys(e).forEach((k) => {
    if (!acc[k]) acc[k] = [];
    if (!acc[k].includes(e[k])) acc[k].push(e[k]);
  });
  return acc;
}, {});

console.log(transformed);

If for one of the object keys (sex or name in this case) a value array does not exist, it is created. Before a value is pushed into any of the value arrays, it is verified that it is not already present in that array.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement