I have a dictionary of arrays as follow:
var usersTemp = {11: [ {"active": true, "email": "[email protected]", "userid": 2, } ],
12: [ {"active": true, "email": "[email protected]", "userid": 1, },
{"active": true, "email": "[email protected]", "userid": 2, } ], }
I need to merge the elements that have the same email address or userid and get something similar to this:
{ 1: {"active": true, "email": "[email protected]", "roles": [12]} ,
2: {"active": true, "email": "[email protected]", "roles": [11 , 12]}, }
This is my try:
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);
}
}
But the problem is deep copy in javascript and it's returning the same value for the user info. How can I fix it?
useris the index in the array, not the user ID. Tryvar uid = usersTemp[role][user]['userid'];and use that inif(!mergedUsersTemp[uid])and so on. This seems to give the result you want.for...in...for an array: Why is using “for…in” with array iteration a bad idea?. Not a problem here, but don't let it become a habit :)JSON.parse(JSON.stringify(...))lately? O.o