根据属性值创建多个对象数组,然后遍历每个数组

时间:2013-12-05 16:54:20

标签: javascript jquery arrays object iterator

假设我在数组中有以下对象:

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);
}

希望我的伪代码有意义......

1 个答案:

答案 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"