gpt4 book ai didi

javascript - AngularJS 在属性数组中组合对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:30:30 25 4
gpt4 key购买 nike

我有一大堆对象 (1500+),这些对象在其中一个属性上匹配。因此可以减少对象的总数,例如为了在 ng-repeat 中获得更好的性能。我是 AngularJS 和 JS 本身的新手,非常感谢您的帮助!

我的对象数组(简化)

myArray = [
{
"role": "user111",
"operation": "create",
"concept": "folder"
},
{
"role": "user111",
"operation": "create",
"concept": "task"
},
{
"role": "user111",
"operation": "delete",
"concept": "task"
},
{
"role": "user222",
"operation": "create",
"concept": "folder"
},
{
"role": "user222",
"operation": "create",
"concept": "task"
},
{
"role": "user222",
"operation": "delete",
"concept": "task"
}
]

期望的输出

dreamArray = [
{
"role": "user111",
"operation": {
"create": ["folder", "task"],
"delete": ["task"]
}
},
{
"role": "user222",
"operation": {
"create": ["folder", "task"],
"delete": ["task"]
}
}
]

最佳答案

您可以使用 forEach() 循环和 thisArg 参数来做到这一点。

var myArray = [{"role":"user111","operation":"create","concept":"folder"},{"role":"user111","operation":"create","concept":"task"},{"role":"user111","operation":"delete","concept":"task"},{"role":"user222","operation":"create","concept":"folder"},{"role":"user222","operation":"create","concept":"task"},{"role":"user222","operation":"delete","concept":"task"}]

var result = [];
myArray.forEach(function(e) {
if(!this[e.role]) {
this[e.role] = {role: e.role, operation: {[e.operation]: [e.concept]}}
result.push(this[e.role]);
} else {
var op = this[e.role].operation[e.operation]
if(op) op.push(e.concept)
else this[e.role].operation[e.operation] = [e.concept]
}
}, Object.create(null))


console.log(result)

关于javascript - AngularJS 在属性数组中组合对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44415163/

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