gpt4 book ai didi

javascript - 根据属性值创建多个对象数组,然后迭代每个数组

转载 作者:行者123 更新时间:2023-11-28 20:08:08 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

关于javascript - 根据属性值创建多个对象数组,然后迭代每个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20405961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com