我正在收集一组数据,它们输出的内容如下:
[
{
hostName: 'server1',
service: 'service1',
perfData: 'unique string5',
state: 1
},
{
hostName: 'server1',
service: 'service2',
perfData: 'unique string4',
state: 1
},
{
hostName: 'server1',
service: 'service3',
perfData: 'unique string3',
state: 1
},
{
hostName: 'server2',
service: 'service1',
perfData: 'unique string2',
state: 1
},
{
hostName: 'server2',
service: 'service2',
perfData: 'unique string1',
state: 1
}
]
我正在尝试使用javascript遍历此对象数组以输出以下内容:
let desiredOutput = [{'server1': [{
service: 'service1',
perfData: 'unique string1',
state: 1
},
{
service: 'service2',
perfData: 'unique string1',
state: 1
},
{
service: 'service3',
perfData: 'unique string1',
state: 1
}],
'server2': {
service: 'service1',
perfData: 'unique string1',
state: 1
}
}];
JavaScript是否具有类似于dict理解的功能?不确定如何遍历对象数组并合并它们并使它们成为具有对象数组的对象。在python中,我可以使用如下代码:
raw_data = [{'hostName': 'server1', 'serviceName': 'service1'}, {'hostName': 'server1', 'serviceName': 'service2'}, {'hostName': 'server1', 'serviceName': 'service3'}, {'hostName': 'server2', 'serviceName': 'service1'}, {'hostName': 'server2', 'serviceName': 'service2'}]
services = defaultdict(list)
for service in raw_data:
host_name = service.get('hostName')
service_name = service.get('service')
new_dict = {'hostName': host_name, 'serviceName': service_name}
services[new_dict['hostName']].append(new_dict)
print(services)
我发现与此Merge javascript objects in array with same key接近,但与我要找的东西不完全相同。
答案 0 :(得分:0)
您的输出结构有点奇怪(一个元素组成的数组?)。使用reduce
是一种合理的方法,为每个唯一键构建数组:
const data = [ { hostName: 'server1', service: 'service1', perfData: 'unique string5', state: 1 }, { hostName: 'server1', service: 'service2', perfData: 'unique string4', state: 1 }, { hostName: 'server1', service: 'service3', perfData: 'unique string3', state: 1 }, { hostName: 'server2', service: 'service1', perfData: 'unique string2', state: 1 }, { hostName: 'server2', service: 'service2', perfData: 'unique string1', state: 1 } ];
console.log([data.reduce((a, e) => {
const name = e.hostName;
delete e.hostName;
a[name] = name in a ? a[name].push(e) && a[name] : [e];
return a;
}, {})]);