【问题标题】:Create multiple arrays of objects based on property value then iterate through each array根据属性值创建多个对象数组,然后遍历每个数组
【发布时间】:2013-12-22 17:53:29
【问题描述】:

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

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

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

【问题讨论】:

  • 调试伪代码真的很难。尝试将其转换为 JavaScript,如果出现任何问题,请告诉我们。
  • var entities = [server1: 无效,[ 应该是 {(不要忘记修复关闭)

标签: javascript jquery arrays object iterator


【解决方案1】:

一个简单的 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"

【讨论】:

  • 这看起来不错,那么我该如何解决第 28 行的问题:jsfiddle.net/scottbeeson/D5E77/4
  • @ScottBeeson: Object.keys(typeArray) 将返回一个字符串数组,其中包含最初包含在实体变量中的任何类型的唯一名称。
猜你喜欢
  • 1970-01-01
  • 2020-09-03
  • 1970-01-01
  • 1970-01-01
  • 2014-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
相关资源
最近更新 更多