使用对象中的键从对象列表中创建映射
create a map out of list of objects using a key found in the object
本质上,我有一个像这样的对象-
var data= [
{ id: 1,
objectType: 'Workstation',
isUp: true
},
{ id: 2,
objectType: 'Workstation',
isUp: true
},
{ id: 3,
objectType: 'Workstation',
isUp: false
},
{ id: 4,
objectType: 'Workstation',
isUp: true
},
{ id: 5,
objectType: 'Workstation',
isUp: false
},
{ id: 6,
objectType: 'Server',
isUp: true
},
{ id: 7,
objectType: 'Server',
isUp: true
},
{ id: 8,
objectType: 'Server',
isUp: false
},
{ id: 9,
objectType: 'Server',
isUp: false
}
]
其中"isUp"是联机或脱机对象状态。
我想把它转换成-
{
'Workstation':{online_count:3, offline_count:2},
'Server':{online_count:2, offline_count:2}
}
感谢您的帮助!
我为您准备了dis脚本:
var data= [
{ id: 1,
objectType: 'Workstation',
isUp: true
},
{ id: 2,
objectType: 'Workstation',
isUp: true
},
{ id: 3,
objectType: 'Workstation',
isUp: false
},
{ id: 4,
objectType: 'Workstation',
isUp: true
},
{ id: 5,
objectType: 'Workstation',
isUp: false
},
{ id: 6,
objectType: 'Server',
isUp: true
},
{ id: 7,
objectType: 'Server',
isUp: true
},
{ id: 8,
objectType: 'Server',
isUp: false
},
{ id: 9,
objectType: 'Server',
isUp: false
}
]
var finalData = new Array();
data.forEach(function (item) {
var found = false;
for (var i = 0; i < finalData.length; i++) {
if (finalData[i].objType == item.objectType) {
if (item.isUp)
finalData[i].online_count++;
else
finalData[i].offline_count++;
found = true;
}
}
if (!found) {
var newObj = new Object();
newObj.objType = item.objectType;
newObj.online_count = item.isUp ? 1 : 0;
newObj.offline_count = item.isUp ? 0 : 1;
finalData.push(newObj);
}
});
console.log(finalData);
我认为这可以做到:
var result = {
Workstation: {
online_count: 0,
offline_count: 0
},
Server: {
online_count: 0,
offline_count: 0
}
};
data.forEach(function (item) {
item.isUp ? result[item.objectType]['online_count']++ : result[item.objectType]['offline_count']++;
});
相关文章:
- 如何使用json将对象列表从java转换为javascript
- 从HTTPGET返回一个自定义对象列表,以便在Angular 2应用程序中使用
- 当属性不一致时,如何根据属性对JS对象列表进行排序
- 无法在mvc视图中使用ajax调用获取操作返回的模型对象列表
- 如何从类关系中检索对象列表
- 从Javascript动态构建JSON对象列表
- 如何在JSP中对对象列表进行排序
- 什么'是从对象列表中一次编辑一个对象的正确Angular/Firebase方法
- 无法将对象列表从视图模型设置为 javascript 变量
- 如何将对象插入对象列表的开头,当它有 unshift 不是函数错误
- 下划线,将对象列表转换为对象值数组
- 以有效的方式搜索对象列表 mongo
- 如何将对象列表传递到MVC4中的控制器方法
- 为什么更改对象列表中的类名会将iten从列表中删除
- 遍历对象列表
- 将JSON对象列表传递给操作
- 如何从控制器返回对象列表并使用JQuery(SpringMVC,ajax)显示它们
- 从jQuery数组或元素的对象列表中选择第N个项目
- 将jsp对象列表分配给javascript数组
- Javascript:将对象列表转换为关联数组