在javascript中克隆变量不起作用

时间:2017-03-10 16:01:17

标签: javascript

我有一个数组字典如下:

var usersTemp = {11: [ {"active": true, "email": "seconduser@example.com", "userid": 2, } ],
            12:  [ {"active": true, "email": "firstuser@example.com", "userid": 1, },
                   {"active": true, "email": "seconduser@example.com", "userid": 2, } ], }

我需要合并具有相同电子邮件地址或用户ID的元素,并获得与此类似的内容:

{ 1: {"active": true, "email": "firstuser@example.com", "roles": [12]} ,
  2: {"active": true, "email": "seconduser@example.com", "roles": [11 , 12]}, }

这是我的尝试:

var mergedUsersTemp = {};
for (var role in usersTemp) {
    for (var user in usersTemp[role]) {
        if(!mergedUsersTemp[user]){
            const i = JSON.parse(JSON.stringify(usersTemp[role][user]));
            console.log(JSON.stringify(i))
            mergedUsersTemp[user] = {"active": i["active"], "email": i["email"], "id": i["id"], "roles": []};
            mergedUsersTemp[user]["roles"] = [];
        }
        mergedUsersTemp[user]["roles"].push(role);
    }
}

但问题是javascript中的深层复制,并且它返回了用户信息的相同值。我该如何解决?

1 个答案:

答案 0 :(得分:1)

而不是for...in循环,更容易使用Object.keys()forEach循环。然后,您只需先检查对象中是否已存在userid并设置其值或添加到角色并更改为活动状态。

var usersTemp = {
  11: [{
    "active": true,
    "email": "seconduser@example.com",
    "userid": 2,
  }],
  12: [{
    "active": true,
    "email": "firstuser@example.com",
    "userid": 1,
  }, {
    "active": true,
    "email": "seconduser@example.com",
    "userid": 2,
  }],
}

var result = {}
Object.keys(usersTemp).forEach(function(i) {
  usersTemp[i].forEach(function(j) {
    if (!result[j.userid]) {
      result[j.userid] = {
        active: j.active,
        email: j.email,
        roles: []
      }
    }
    result[j.userid].roles.push(i)
    result[j.userid].active = j.active
  })
})

console.log(result)