"Tips on updating the value of a BehaviorSubject with map, filter, find, or findIndex in an Angular

TS

  arrData = new BehaviorSubject<any>([]);

  ngOnInit() {
    const dataArr1 = [
      {
        id: '1',
        name: 'Room1',
        spinning: true
      },
      {
        id: '2',
        name: 'Room2',
        spinning: true
      },
      {
        id: '3',
        name: 'Room3',
        spinning: true
      },
      {
        id: '4',
        name: 'Room4',
        spinning: true
      }
    ];

    this.arrData.next(dataArr1);

    const url = { id: '2', name: 'Room2', link: '/api/conditions'}
    const arr = new Array();
    arr.push(url);

    this.arrData.value.map((item: any) => {
      return {
        id: item.id,
        name: item.name,
        spinning: arr.findIndex(e => {
          return e.id === item.id
        }) === -1
      }
    });
    console.log(this.arrData.value);
  }

Here is a sample output: https://stackblitz.com/edit/angular-msovvq?file=src/app/app.component.ts

The aim here is to modify the value of spinning to false.

In the given example, there's a data object { id: 2, name: 'Room2' }, which I then push to create an array.

I'm using findIndex where dataArr1 id === arr id, but it doesn't change the spinning value to false in dataArr1.

It remains the same.

[
      {
        id: '1',
        name: 'Room1',
        spinning: true
      },
      {
        id: '2',
        name: 'Room2',
        spinning: true
      },
      {
        id: '3',
        name: 'Room3',
        spinning: true
      },
      {
        id: '4',
        name: 'Room4',
        spinning: true
      }
    ];

It should look like this.

[
      {
        id: '1',
        name: 'Room1',
        spinning: true
      },
      {
        id: '2',
        name: 'Room2',
        spinning: false
      },
      {
        id: '3',
        name: 'Room3',
        spinning: true
      },
      {
        id: '4',
        name: 'Room4',
        spinning: true
      }
    ];

The Room2 spinning will be changed to false.

Answer №1

To optimize your code, it's recommended to utilize both map and filter functions together. This way, a new array is returned without altering the original values, requiring you to assign the result back to the variable.

dataArr1 = dataArr1.map(item => {
  return {
    id: item.id,
    name: item.name,
    spinning: dataArr2.findIndex(e => e.id === item.id) === -1
  }
})

Check out the updated array below to see if it meets your expectations:

[
  {
    "id": "1",
    "name": "Room1",
    "spinning": false
  },
  {
    "id": "2",
    "name": "Room2",
    "spinning": false
  },
  {
    "id": "3",
    "name": "Room3",
    "spinning": false
  },
  {
    "id": "4",
    "name": "Room4",
    "spinning": true
  }
]

Answer №2

Utilizing the lodash library

let data = [
      {
        id: '1',
        name: 'Room1',
        spinning: true
      },
      {
        id: '2',
        name: 'Room2',
        spinning: true
      },
      {
        id: '3',
        name: 'Room3',
        spinning: true
      },
      {
        id: '4',
        name: 'Room4',
        spinning: true
      }
    ];

Considering we only need to locate items based on their id:

let itemUrl =  { id: '2', name: 'Room2', link: '/api/conditions'}

let foundItem= _.find(data, {id: itemUrl['id']})
foundItem.spinning = false

Once you identify the element according to your criteria, you have the flexibility to adjust the object properties to suit your needs. As this object is not duplicated, any changes made will directly impact the main array of objects.

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

Sending JSON array from PHP to jQuery AJAX

Currently, I am working on an experimental project where I need to search for a product in a MySQL database using the product name and retrieve the price in the 'price input' field and sell price in the 'sellprice input' field. You can ...

Please submit the form triggered by a JavaScript event

I am looking to create a form that can be submitted when a user presses a key, such as tab or enter, which would cause them to lose focus. Additionally, clicking outside of the text field should also trigger a submit action. However, if the user clicks on ...

Creating a binary tree in vanilla JavaScript and styling it with HTML and CSS

I'm facing a challenge with my homework. I am required to convert my JavaScript binary tree into HTML and CSS, strictly using vanilla JavaScript without any HTML code. I have the tree structure and a recursive function that adds all the tree elements ...

What is the process for deselecting text from a text field?

After performing a search and displaying the results on my search form, I've noticed that the text query in the textfield is being marked as selected text even though I don't want it to be. How can I prevent this? Fiddle 1) What is the best app ...

Utilizing JQuery to update the selected item in a menu

Hey there! I'm currently using the jquery chosen plugin and I'm trying to make it so that I can select a menu value based on the selection from another select menu. Unfortunately, my code only works with a simple select menu and I need it to work ...

What events precede and follow a keydown action in a Textarea field?

I need to prevent users from pressing function keys (F1, F2, etc.), the tab key, and any other characters from being added. The code below is supposed to achieve this on my website but it's not working. document.getElementById("code").addEventList ...

What could be the reason for this code returning a "module not found" error?

Within localbase.js... const fs = require("fs"); if(!fs.existsSync(__dirname + "/localbase.json")) fs.writeFileSync("./localbase.json", "{}"); let database = require("./localbase.json"); The code abov ...

Pagination and Rowspan features malfunctioning in Material Table

Currently, I'm encountering a problem when trying to paginate a material table with rowspan. The binding of the rowspan attribute works correctly by itself. However, once pagination is implemented, it results in the duplication of values. For instance ...

Storing a complete Bootstrap 3 <div> element in a JavaScript array

Hey there, I'm fairly new to the world of web development and I've been working on incorporating a collection of images and containers within a div array. The goal is to be able to hide the entire div using (display: none) and then show another d ...

A TypeError is thrown when attempting to use window[functionName] as a function

I came across this page discussing how to call a function from a string. The page suggests using window[functionName](params) for better performance, and provides an example: var strFun = "someFunction"; var strParam = "this is the parameter"; //Creating ...

Tips for validating an object with unspecified properties in RunTypes (lowercase object type in TypeScript)

Can someone please confirm if the following code is correct for validating an object: export const ExternalLinks = Record({}) I'm specifically asking in relation to the repository. ...

Instructions on adding the modified data to the list in AngularJS without relying on a database

Currently, I am working on an app development project using Ionic and AngularJS. The main feature of the app is to display a list of car brands along with their respective models in the first UI view. Once a user selects a car brand from the list, they a ...

Angular5 - Modify a public variable using an intercept in a static service

Take into account the following Angular service: @Injectable() export class AuthService { public userConnected: UserManageInfo; getManageInfo(): Observable<UserManageInfo> { return this.httpClient .get('api/Account/Man ...

Ways to resolve the array to string conversion issue in PHP

In my PHP project, I am dealing with a dynamic array and trying to store the array result in a variable. However, I encountered an error: array to string conversion while coding. <?php require_once('ag.php'); class H { var $Voltage; ...

Angular array: Cannot access property of undefined - Type Error

Having trouble fetching data from a web service? I keep encountering the same error message that says "ERROR TypeError: Cannot read property 'bu' of undefined", even though the data I want to show is appearing correctly. Check out the response an ...

Tips for deleting multiple values from an array in Angular 2

When choosing multiple ion-items from a list, I am looking to eliminate identical items from an array. HTML Code <div class="ion-item optionalItem"> <button class="ion-button" ion-item *ngFor="let configop of interiorOption" (click)="itemSel ...

Issues with jQuery fundamentals

For a while now, I've been grappling with jQuery. It's undeniably powerful and offers a plethora of fantastic capabilities. However, my struggle lies in the fact that I tend to incorporate multiple jQuery features simultaneously. For example, on ...

Angular reduces image width to zero

Looking to include an image in an Angular template, where the width attribute is equal to a variable width that sometimes holds the value null. In cases where width = null, I aim to have width = "" (or no width attribute at all). However, Angular assigns ...

Creating a variable in Node.js to serve as the name of a nested element within an object

Check out the object I have: obj = { "FirstName": "Fawad", "LastName": "Surosh", "Education": {"University": "ABC", "Year": "2012"} } Take a look at my node.js script: var nodeName = 'Education.Year'; obj.nodeName; // ...

A schema already exists with the key or ID "http://json-schema.org/draft-06/schema"

While attempting to include the Material library in my Angular project using npm install --save @angular/material @angular/cdk, I encountered some issues as described in this question: Error TS2315: Type 'ElementRef' is not generic material angul ...