假设我在数组中有以下对象:
var entities = [
server1: { type: server },
server2: { type: server },
server3: { type: server },
printer1: { type: printer },
printer2: { type: printer },
printer3: { type: printer },
switch1: { type: switch },
switch2: { type: switch },
switch3: { type: switch }
]
我怎么能这样做:
typeArray(type) = []
for each type in entities {
for each entity in entities of type {
typeArray(type).push(entity)
}
}
这应该会导致类似......
typeArray("switch")(0) = switch1
typeArray("server")(2) = server3
typeArray("printer")(1) = printer2
最重要的是,我希望能够以编程方式访问所有数组
for each typeArray() {
var type = ???
myArrayFunction(typeArray, type);
}
希望我的伪代码有意义......
答案 0 :(得分:3)
一个简单的map()会为你重新洗牌:
var entities = {
server1: { type: 'server' },
server2: { type: 'server' },
server3: { type: 'server' },
printer1: { type: 'printer' },
printer2: { type: 'printer' },
printer3: { type: 'printer' },
switch1: { type: 'switch' },
switch2: { type: 'switch' },
switch3: { type: 'switch' }
}
var typeArray={};
Object.keys(entities).map(function(a){
var v=this[a];
typeArray[v.type]=typeArray[v.type]||[];
typeArray[v.type].push(a);
},entities);
typeArray /* ==
{
"server": [
"server1",
"server2",
"server3"
],
"printer": [
"printer1",
"printer2",
"printer3"
],
"switch": [
"switch1",
"switch2",
"switch3"
]
}
*/
// a sanity check for your suggested code seems to work using js syntax:
typeArray["server"][2] // == "server3"