Let's say I have this object:
{
b954WYBCC4YbsMM36trawb00xZ32: { activity1: "pending", activity2: "pending" },
pby0CAqQ1hTlagIqBTQf6l2Ti9L2: { activity1: "pending", activity2: "pending" }
}
where the first keys are IDs from a database. I want to be able to change the values of activity1
and activity2
based on an array:
// 'data' is the object mentioned above.
const usersHaveSpecialContentAssigned = [true, false];
Object.values(data).forEach((item, index) => {
const arrayActivityProgress = Object.values(item as string[]);
if (usersHaveSpecialContentAssigned[index] === false) {
arrayActivityProgress.forEach((progress) => {
progress = 'unassigned';
console.log(progress);
});
}
});
As you can see, my goal is to change the values of activity1
and activity2
if the corresponding value in usersHaveSpecialContentAssigned
is false
.
The end result based on the example above should look like this:
{
b954WYBCC4YbsMM36trawb00xZ32: { activity1: "pending", activity2: "pending" },
pby0CAqQ1hTlagIqBTQf6l2Ti9L2: { activity1: "unassigned", activity2: "unassigned" }
}
How can I archieve this? My current approach doesn't update the values.
CodePudding user response:
You can write
Object.values(data).forEach((item, index) => {
if (!usersHaveSpecialContentAssigned[index])
item.activity1 = item.activity2 = "unassigned";
You of course need to watch for the index not to be out of range.
CodePudding user response:
As you already know what the ids are going to be, I would write it this way.
var initialData = {
b954WYBCC4YbsMM36trawb00xZ32: { activity1: "pending", activity2: "pending" },
pby0CAqQ1hTlagIqBTQf6l2Ti9L2: { activity1: "pending", activity2: "pending" }
};
var permissionsPerUserDataIn = {"b954WYBCC4YbsMM36trawb00xZ32": true, "pby0CAqQ1hTlagIqBTQf6l2Ti9L2": false, "id3": false};
and write your function like this:
function fixData(permissionsPerUser) {
for (var [id, values] of Object.entries(initialData)) {
if (permissionsPerUser.hasOwnProperty(id) && !permissionsPerUser[id]) {
values.activity1 = 'unassigned';
values.activity2 = 'unassigned';
console.log(`${id}: `, values);
}
}
}
fixData(permissionsPerUserDataIn);
Doing it this way will give you more granular control over what permissions will get updated and you will not have to worry if a value in the array gets out of sync for whatever reason.