![](/img/trans.png)
[英]Underscore.js: create a map out of list of objects using a key found in the object
[英]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}
}
任何幫助表示贊賞!
我為您准備了劇本:
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']++;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.