如何解决将数组中相同键的值合并到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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。