Home > Mobile >  convert array of objects to map of field values structure javascript
convert array of objects to map of field values structure javascript

Time:09-16

I have an array of objects like this:

const arr=[
{ name:"test",
  class:3
},
{ name:"test2",
  class:4
},
{ name:"test3",
  class:5
},]

Now I have to convert it to a map like structure as shown below:

const map={
"name":["test","test2","test3"],
"class":[3,4,5]
}

I am clueless on how to make this kind of structure.Any leads will be appreciated.

CodePudding user response:

If you have an arbitrary amount of keys you can use Object.entries() to get all the key value pairs. Then just loop over all entries and add them to the final output.

const arr=[{name:"test",class:3},{name:"test2",class:4},{name:"test3",class:5}];

const map = arr.reduce((acc, obj) => {
  for(const [key, value] of Object.entries(obj)) {
    if(acc[key]) {
      acc[key].push(value);
    }else{
      acc[key] = [value];
    }
  }
  
  return acc;
}, {});

console.log(map);

CodePudding user response:

Have a function that accepts the array and the property you're looking for, and return a new array of data using map for each property of your new object.

const arr=[{name:"test",class:3},{name:"test2",class:4},{name:"test3",class:5}];

function getData(arr, prop) {
  return arr.map(obj => obj[prop]);
}

const map = {
  name: getData(arr, 'name'),
  class: getData(arr, 'class')
}

console.log(map);

CodePudding user response:

It should be something like that

arr.reduce((res, obj) => {
   Object.entries(obj).forEach(([k,v]) =>     {
     if(!res[k]) res[k] = []
     res[k].push(v)
   })
    return res
},{})
  • Related