-1

My array looks like below

const arr = [
      {
        "devices": "delete"
      },
      {
        "devices": "update"
      },
      {
        "devices": "read"
      },
      {
        "alerts":"read"
      }
    ]

I have to change the format as below :

const dict =  {
"devices": [
"update",
"read"
],
"alerts": [
"read"
]}

Is there a optimal way to achieve this ?

naveen
  • 107
  • 1
  • 1
  • 10

2 Answers2

1

Yes. You need to create a empty dictionary. If item or key is not present in dictionary then create the key in dictionary and assign an empty array.Now insert item in it.

const arr = [{
    "devices": "delete"
  },
  {
    "devices": "update"
  },
  {
    "devices": "read"
  },
  {
    "alerts": "read"
  }
];

const dict = {};
arr.forEach(item => {
  const key = Object.keys(item);
  if (!dict[key]) {
    dict[key] = [];
  }
  dict[key].push(item[key]);

})

console.log(dict);
Ivar
  • 6,138
  • 12
  • 49
  • 61
deepak
  • 1,390
  • 1
  • 8
  • 12
1

You can reduce it!

const arr = [
      {
        "devices": "delete"
      },
      {
        "devices": "update"
      },
      {
        "devices": "read"
      },
      {
        "alerts":"read"
      }
    ]
    
let dict = arr.flatMap(el => Object.entries(el)).reduce((a,[key, value]) => {
   if(key in a) {
      a[key].push(value);
      return a;
   }
   a[key] = [value];
   return a;
},{})

console.log(dict);
bill.gates
  • 14,145
  • 3
  • 19
  • 47