Understanding the correct way to map two arrays with boolean values is essential for effective data

My situation involves two lists: accounts and accountsWithSelectedField. I initially mapped accountsWithSelectedField like this:

this.accountsWithSelectedField = this.accounts.map(s => ({...s, selected: false}));

Subsequently, upon receiving a list of selected accounts called accountsSetups from an http request, I need to update the mapping accordingly. The desired outcome should be as follows:

accounts: 111, 222, 333, 444
accountsWithSelectedField: {111: false}, {222: false}, {333: false}, {444: false}
accountSetups(from http): {222, true, true}, {333, true, false}
After mapping => accountsWithSelectedField: {111: false}, {222: true}, {333: true}, {444: false}

I am struggling with correctly mapping it, as my attempts either do not display the IBAN or result in all selections being marked as true.

this.accountsWithSelectedField = this.accounts.map(o => data.accountSetups.map(s => ({
       iban: o.iban,
       selected: s.someBoolean || s.anotherBoolean
     })));

I have also tried another approach:

for (const account of this.accountsWithSelectedField) {
      for (const acc of data.accountSetups) {
        if (account.iban === acc.account.iban) {
          console.log(account.iban + ' is true');
          account.selected = true;
        }
      }
    }

Although I achieved 3 out of 6 IBANs being marked as true correctly, all six were ultimately selected, which is puzzling to me.

Answer №1

Here's a possible approach you could take:

const users = ["Alice", "Bob", "Eve", "John"];
const usersWithStatus
  = users.map(user => ({name: user, isActive: false}));
const activeUsers = [
  {name: "Bob", isActive: true},
  {name: "Eve", isActive: true}
];

for (const activeUser of activeUsers) {
  const associatedUser = usersWithStatus.find(user => user.name === activeUser.name);
  if (associatedUser) {
    associatedUser.isActive = activeUser.isActive;
  }
}

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

Tips for avoiding parent div click interference in Angular

Working with Angular8, I have a div containing a routelink along with other components including a checkbox. Here's the structure: <div [routerLink]="['/somewhere', blablabla]"> <!--other components that navigate to the ro ...

NuxtJS (Vue) loop displaying inaccurate information

I have a dataset that includes multiple languages and their corresponding pages. export const myData = [ { id: 1, lang: "it", items: [ { id: 1, title: "IT Page1", }, { ...

Tips for waiting for an observable loop

When using my application, the process involves uploading a series of images in order to retrieve the file IDs from the system. Once these IDs are obtained, the object can then be uploaded. async uploadFiles(token: string):Promise<number[]> { let ...

Using the RabbitMQ consume method in conjunction with the channel.ack function

I'm currently working on a function in TypeScript to consume messages from my RabbitMQ: async consume( queue: string, callback: (message: ConsumeMessage | null) => void, ) { return this.channel.consume(queue, message => { c ...

Differences between Angular TS Lint onInit and ngOnInit

My TS Lint issue warned me to implement the OnInit interface and included a link to this page: https://angular.io/docs/ts/latest/guide/style-guide.html#!#09-01 I'm curious, what sets apart `onInit` from `ngOnInit`? Both seem to work just fine for me. ...

What is preventing me from installing Angular Bootstrap?

Version Information: Angular CLI: 14.2.3 Node: 16.15.1 Package Manager: npm 8.12.1 Operating System: darwin x64 Encountered an error while trying to install Angular Bootstrap using NPM: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! ...

A different approach to routing in Next.js with getServerSideProps

Let's say I have a dynamic route in my application, with the name [id] Typically, I use getServerSideProps in the pages router to validate any properties passed to the route. It usually looks something like this: export async function getServerSidePr ...

Tips for refreshing the current page in Angular without being redirected to the login page

Exploring an Angular example for login and registration here on stackblitz Encountering an issue where after refreshing the page, the authguard redirects me to the login page even though I am already logged in. Looking for a solution to redirect to the c ...

Angular Space-Friendly Table

After attempting to code the sample in Angular, I realized it wasn't what I was looking for. <table> <th >Number</th> <th >Merchant Name</th> ...

What is the best way to extract specific fields from nested tables using MikroORM?

I am currently facing challenges while attempting to extract specific fields from nested join results. Within my entities, there is a "Restaurant" entity that has a one-to-many relationship with "Product". Each "Product" has a many-to-many relationship wi ...

Error encountered when trying to update tree structure in TypeScript with new data due to incorrect array length validation

I have encountered an issue with my tree data structure in TypeScript. After running the updateInputArray(chatTree); function, I am getting an “invalid array length” error at the line totalArray.push(iteratorNode.data);. Furthermore, the browser freeze ...

An issue detected in the index.esm.js file located in the firebase/firestore module within the node

I've encountered an issue while starting my angular project using the npm-start command. Here is the error I came across: ERROR in ./node_modules/firebase/firestore/dist/index.esm.js Module not found: Error: Can't resolve '@firebase/firest ...

Explaining the structure of a nested object within a TypeScript declaration file

As I work on my project, I encounter the challenge of importing an object created by a dynamic function. The dynamic nature of the keys on this object poses a problem for the IDE, as it cannot determine what keys are present based on the provided config. T ...

React / NextJS: Repeating Audiowave Component

I am currently developing a chat application in NextJS that includes text-to-speech functionality. To visualize the audio playback waveform, I have integrated a third-party library called wavesurfer.js Though the audio implementation is functioning proper ...

What is the process for combining an object and a primitive type to create a union type?

Having a tricky time with Typescript and finding the correct typing for my variable. What seems to be the issue? The variable selected in my code can either be of type DistanceSplit or number. I have an array that looks like this: [-100, DistanceSplit, D ...

"Unfortunately, SockitIO is repeatedly running into issues with being blocked by

I keep encountering an error in my application (using Node.js as API) and Angular 8 as frontend. The error message says: Access to XMLHttpRequest at 'http://localhost:3000/socket.io/?EIO=3&transport=polling&t=NQJpoTm' from origin 'ht ...

Incorporating an additional ion-item alongside the existing one instead of substituting it

I am retrieving a list of questions from an API with pagination. I have a button that triggers a function to load the next page of questions. Instead of replacing the previous page, I want to append the new questions below the existing ones. Here is my cur ...

Utilizing an Angular component for multiple purposes

For my Angular app, which is component-based and uses Angular version 1.5.5 with TypeScript, I have a header component that includes a country dropdown. This header component is used across multiple pages. However, when a country is selected from the dropd ...

Collaborating on a project that has been developed using various editions of Typescript

Currently, I am part of a team working on a large project using Typescript in Visual Studio. As we have progressed through different versions of the project, we have encountered an issue with versioning the installed TypeScript within Visual Studio. Situa ...

Contrast between employing typeof for a type parameter in a generic function and not using it

Can you explain the difference between using InstanceType<typeof UserManager> and InstanceType<UserManager> I'm trying to understand TypeScript better. I noticed in TS' typeof documentation that SomeGeneric<typeof UserManager> ...