Modifying data within nested objects using Typescript

Imagine having an object like this:

{
   b954WYBCC4YbsMM36trawb00xZ32: { activity1: "pending", activity2: "pending" },
​   pby0CAqQ1hTlagIqBTQf6l2Ti9L2: { activity1: "pending", activity2: "pending" }
}

with the initial keys being IDs retrieved from a database. The objective is to alter the values of activity1 and activity2 based on an array:

// 'data' refers to the object mentioned earlier.
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);
        });
    }
});

The desired outcome following the example above should be:

{
   b954WYBCC4YbsMM36trawb00xZ32: { activity1: "pending", activity2: "pending" },
​   pby0CAqQ1hTlagIqBTQf6l2Ti9L2: { activity1: "unassigned", activity2: "unassigned" }
}

Is there a way I can accomplish this? My current method isn't effectively updating the values.

Answer №1

When anticipating the specific ids, it is best to structure the code in this manner.

var startingData = {
   b954WYBCC4YbsMM36trawb00xZ32: { activity1: "pending", activity2: "pending" },
   pby0CAqQ1hTlagIqBTQf6l2Ti9L2: { activity1: "pending", activity2: "pending" }
};
var permissionsPerUserInputs = {"b954WYBCC4YbsMM36trawb00xZ32": true, "pby0CAqQ1hTlagIqBTQf6l2Ti9L2": false, "id3": false};

Here is how you can define your function:

function adjustData(userPermissions) {

    for (var [id, vals] of Object.entries(startingData)) {
       if (userPermissions.hasOwnProperty(id) && !userPermissions[id]) {  
           vals.activity1 = 'unassigned';
           vals.activity2 = 'unassigned';
           console.log(`${id}: `, vals);
       }
    }
}

adjustData(permissionsPerUserInputs);

This approach provides more precise control over permission updates and prevents potential synchronization issues within the array.

Answer №2

You have the ability to compose

Utilize Object.values(data) to iterate through each item with its corresponding index in a function that assigns "unassigned" to both activity1 and activity2 if usersHaveSpecialContentAssigned[index] is false.

Always ensure you are monitoring the index range to prevent any errors.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can a strict type be created from a partial type?

By utilizing TypeScript 2.1, we have the ability to generate a partial type from a strict type as demonstrated below: type Partial<T> = { [P in keyof T]?: T[P]; }; type Person = { name: string, age: number } type PersonPartial = Partial<Pers ...

Leveraging JavaScript event handlers within a progress wizard located within an update panel

I need assistance with implementing a password strength meter for a textbox within a wizard control. The issue I'm facing is that the password box does not become visible until step 4, preventing me from registering an event handler onload(). Placing ...

Is it possible to execute a Google Script on the last row of a spreadsheet exclusively

I have an email script that is functioning correctly, but I only want it to run through the last row with data in it. If there is no data in a row, then I do not need the script to run for that specific row. How can I modify the example script below to ref ...

Why am I unable to apply the keyof operator from one type to another type, even though both types have identical keys defined but different value types?

Consider this code snippet. I am encountering a TypeScript error specifically on the last compat[k] line with the following error message: Type 'keyof T' cannot be used to index type 'Partial<CompatType>' export type KeysOfType ...

Is it necessary to have NodeJs in order to host a React app on a server?

I've been working on a .NET Core 2.2 project with React integration, As I'm nearing completion of the project, I have a query that has been on my mind. Do I need Node.js installed on the server for React to function properly? Thank you. ...

Navigating by Typing in the URL Bar in React

Whenever I paste a valid URL and press enter, the useEffect function in the parent component does not get triggered. However, if I reload the page, it works fine. Here is the code snippet: Routing path <Route path="/search" element={<Searc ...

After the execution of the script by V8, which phase will be initiated first?

Scenario // test.js setTimeout(() => console.log('hello'), 0) setImmediate(() => console.log('world')) Simply execute node test.js using node v12.12.12 on an Intel MacBook Pro. The output may vary: hello world Sometimes it is: ...

Tips for updating the position on a website using AJAX

I am developing a website that pulls data from a MySQL database and showcases it on a map. How can I implement an automatic data refresh on the webpage every second? Should I incorporate my AJAX code within a timer function? Do I need to put the PHP scri ...

Encase React black box block components and incorporate DOM event listeners

In my React component, I am using a standard interface to wrap various other components that act as "blackbox" plugins, since I may not have authored them. These plugins must meet certain requirements outlined in the interface to work within the plugin wra ...

When I hover over div 1, I am attempting to conceal it and reveal div 2 in its place

I need help with a CSS issue involving hiding one div on mouse hover and showing another instead. I attempted to achieve this using pure CSS, but both divs end up hidden. Would jQuery be necessary for this task? Below is the CSS/HTML code I wrote: .r ...

Fixing a scrolling element within a div located below the screen is my goal, ensuring it remains fixed in place as the user scrolls

I'm facing a challenge that I need help with: My HTML/CSS layout currently looks like this: Screenshot of how my CSS/HTML appears on the screen upon page load: As I scroll down, I encounter a green element: While scrolling down -> Upon further s ...

Is there a tool or software available that can securely encode a text file into an HTML file without the need for loading it using AJAX?

At the moment, I'm using jQuery to load a txt file (in utf-8) via $.ajax. The txt file has some break lines, such as: line1 line2 line3 When loaded through AJAX into a variable, it appears as: line1\n\nline2\nline3 I could manuall ...

How to retrieve the values of a property from a JavaScript object

Looking for a fresh perspective on this issue. I'm currently retrieving historical data from the cryptocompare API, but I'm having trouble accessing the received values. https://i.sstatic.net/oH6hz.png When I hardcode it as res.data.OMG.USD, I ...

I am interested in duplicating the li elements retrieved from a JSON source

$.getJSON("leftlist.json" , function(data) { $.each(data.articles,function(){ $('#ullist').before("<li id='mylic' style= color:blue class='item new"+cc+"'> "+el.name+"<div class='block'>&l ...

Implement a call feature using ReactJS

My service method involves making a PUT call to an API with an ID parameter. However, I am facing issues with hitting the .put URL. Can someone please verify if this is the correct approach? ENDPOINTS = { SAMPLE: "/sample", }; Below is my ...

The concept of RxJS's catchError function involves the return of a versatile

It's interesting that catchError is returning an Observable union type as Observable<{} | Page} instead of just Observable<Page>. The error message from the compiler reads: Type 'Observable<{} | Page>' is not assignable to t ...

Is it safe to securely store connection credentials in javascript?

I am currently working on developing a web chat app for a Minecraft server using this API. However, the demo script I am referring to displays connection information in plain text, making it easily visible to any client's computer. Is there a way to s ...

What is the counterpart of $.isEmptyObject({}) in Typescript for checking if an object is

Is there a formal method for testing an Object (response from server) to see if it is empty? Currently, I am using jQuery to accomplish this. this.http.post(url, data, {headers: headers}).then( result => { if (!$.isEmptyObject(result ...

Comparing Angular global variables: when to use static readonly in service class versus const

Which method is the better choice? @Injectable({ providedIn: 'root' }) export class MyService { static readonly VALIDITIES = new Map<number, string>([ ... ]); ... } OR: const Validities = new Map<number, string>([ .. ...

What is the process for removing a document attribute in Sanity iO?

I have a collection of objects within my Sanity Document named Images which includes Comments An example comment object in the comments array looks like: { "_key": "6510dc79cf8b", "comment": "Hello world" ...