将数组中相同键的值合并到values数组中

问题描述

我的数组如下所示

#read file lines and edit specific item

file=open("pythonmydemo.txt",'r')
a=file.readlines()
print(a[0][6:11])

a[0]=a[0][0:5]+' Ericsson\n'
print(a[0])

file=open("pythonmydemo.txt",'w')
file.writelines(a)
file.close()
print(a)

我必须更改格式如下:

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

是否有实现此目的的最佳方法

解决方法

是的。您需要创建一个空字典。 如果字典中没有项或键,则在字典中创建键并分配一个空数组。现在在其中插入项。

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);

,

您可以减少它!

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);