Changing the value of an element in an array using typescript within an Angular context

I am currently working with Angular 5 and I have a task to update the array values based on the selectedMobile array. Below is my code snippet:

const mobilelist = [
    { 'key': 'apple', 'name': 'Apple', 'checked': false },
    { 'key': 'sumsung', 'name': 'Sumsung', 'checked': false },
    { 'key': 'oneplus', 'name': 'Oneplus', 'checked': false },
    { 'key': 'mi', 'name': 'Mi', 'checked': false }
  ]; 
const selectedMobile = ['apple']; 
const newmobilelist: any = [];
if (selectedMobile.length > 0) {
  mobilelist.forEach(element => {
    if (selectedMobile.find(x => x == element.key) != null) {
      newmobilelist.push({ 'key': element.key, 'name': element.name, 'checked': true });
    } else {
      newmobilelist.push({ 'key': element.key, 'name': element.name, 'checked': false });
    }
  });
}
console.log(newmobilelist);

Upon checking the console, I am expecting the following result:

[
  { 'key': 'apple', 'name': 'Apple', 'checked': true },
  { 'key': 'sumsung', 'name': 'Sumsung', 'checked': false },
  { 'key': 'oneplus', 'name': 'Oneplus', 'checked': false },
  { 'key': 'mi', 'name': 'Mi', 'checked': false }
];

However, the code is currently returning:

[
  { 'key': 'apple', 'name': 'Apple', 'checked': false },
  { 'key': 'sumsung', 'name': 'Sumsung', 'checked': false },
  { 'key': 'oneplus', 'name': 'Oneplus', 'checked': false },
  { 'key': 'mi', 'name': 'Mi', 'checked': false }
]; 

I am unsure of why this discrepancy is happening. Any help to resolve this issue would be greatly appreciated.

Answer №1

As mentioned previously, your code appears to be operational. Nevertheless, it is overly intricate and can be significantly condensed as shown below.

const mobilelist = [
    { 'key': 'apple', 'name': 'Apple', 'checked': false },
    { 'key': 'sumsung', 'name': 'Sumsung', 'checked': false },
    { 'key': 'oneplus', 'name': 'Oneplus', 'checked': false },
    { 'key': 'mi', 'name': 'Mi', 'checked': false }
];
const selectedMobile = ['apple'];
const newmobilelist = mobilelist.map(x => { x.checked = selectedMobile.includes(x.key); return x});
console.log(newmobilelist)

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

Mastering Nested *ngFor in Angular

I attempted to use nested for loops in Angular but I couldn't achieve the exact result I wanted. I tried different approaches, but none of them gave me the desired outcome from this nested loop function. I am looking to create a select box based on n ...

Changing data types conditionally in Angular using TypeScript

My angular component relies on the API Response for its functionality. I receive these responses from an external API. When there are no errors Data : { Status: string; Data: number; } When an error occurs, this is what I get. Data : { Status: string; ...

Is it necessary to incorporate the OnInit function in Angular 8+ components if I have no intention of modifying it?

I've been working on a project using Angular 8. One thing I've noticed is that when I use the command line to generate components, they are automatically created with OnInit included. For example: export class SideDrawerComponent implements On ...

Trouble with styling the Ngx-org-chart in Angular

I integrated the ngx-org-chart library into my Angular project, but I'm facing issues with the styles not applying correctly. Here are the steps I followed: I first installed the package using: yarn add ngx-org-chart Then, I added the ngx-org ...

The specified type '{ data: any; }' is incompatible with the type 'IntrinsicAttributes'. The property 'data' is not found in the type 'IntrinsicAttributes'

I'm encountering issues with the data property. interface Props { params: { slug: string }; } const Page = async ({ params }: Props) => { const data: any = await getPage(params.slug); // This section dynamically renders the appropriate orga ...

Changing the Value of an Input Element Dynamically in React: A Step-by-Step Guide

In a scenario where I have a component that takes an element, such as <input />, and I need to update its value programmatically after 15 seconds. Initially, I had the following approach in mind: const MyComponent = (myInput: JSX.Element) => { ...

Error: Unable to iterate over data.data due to its type

I am attempting to fetch images from the woocommerce API and here is the code I am using: this.config.getWithUrl(this.config.url + '/api/appsettings/get_all_banners/?insecure=cool') .then((data: any) => { this.banners = data.data; consol ...

What steps are involved in developing an Angular library wrapper for a pre-existing Javascript library?

Imagine having a vanilla Javascript library that is commonly used on websites without any frameworks. How can you create an Angular library that can be easily installed via npm to seamlessly integrate the library into an Angular application? The process o ...

The content security policy is preventing a connection to the signalr hub

Currently, I am developing an application using electron that incorporates React and Typescript. One of the features I am integrating is a SignalR hub for chat functionality. However, when attempting to connect to my SignalR server, I encounter the followi ...

How to define a TypeScript recursive object with a defined endpoint?

Welcome to my first question! I am currently facing an issue with defining an object to store strings in multiple languages. I am looking for a flexible solution and have considered using a nested object structure. However, I want the final object to adhe ...

Setting a property with a generic type array: Tips and tricks

Currently, I am working on implementing a select component that can accept an array of any type. However, I am facing some challenges in defining the generic and where to specify it. My project involves using <script setup> with TypeScript. Here is ...

Tips on launching a bootstrap modal by clicking a button in an Angular project

I'm working with a Bootstrap Modal that includes a button to trigger it. Here is the code: <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data- ...

Creating an Angular Universal Dockerfile and docker-compose.yml file: A step-by-step guide

After struggling to Dockerize my Angular universal app and integrate it with an existing dockerized Spring Boot REST backend, I found myself hitting a wall in terms of available resources and assistance online. Despite making various adjustments, the Docke ...

How are the .map files utilized in angular-cli, and is there a way for ng build to generate these files automatically?

When running ng build with angular-cli, it generates three files: inline.bundle.js vendor.bundle.js main.bundle.js In addition, it also creates a map file for each one. But why? I am wondering if there is a way to customize this process and avoid genera ...

What is the TypeScript equivalent of the Java interface.class?

Can you write a Java code in TypeScript that achieves the same functionality as the code below: Class<?> meta = Object.class; and meta = Processor.class; // Processor is an interface In TypeScript, what would be the equivalent of .class? Specifica ...

Troubleshooting Problem with Installing Angular2-Google-Maps Component in FountainJS Application

Using the FountainJS Angular2 generator with Typescript and Systems.js has been helpful for scaffolding my project. Check it out here However, I encountered an issue while trying to add a component to the project. Upon importing {GOOGLE_MAPS_DIRECTIVES}, ...

Tips for efficiently awaiting outcomes from numerous asynchronous procedures enclosed within a for loop?

I am currently working on a search algorithm that goes through 3 different databases and displays the results. The basic structure of the code is as follows: for(type in ["player", "team", "event"]){ this.searchService.getSearchResult(type).toPromise ...

Issue with TypeScript: Difficulty accessing keys in a recursive manner

I've created a custom type that eliminates any nullish values when working with objects. export type ExcludeNullish<T> = Exclude<T, null | undefined>; export type ExcludeNullishKeys<T> = { [K in keyof T]-?: T[K] extends boolean | ...

Step-by-step guide on how to stop CDK Drop depending on a certain condition

I'm trying to figure out how to disable dropping using CDK based on certain conditions. Specifically, I want the drop functionality to be disabled if the list I'm attempting to drop into is empty. I haven't been able to find a solution withi ...

I possess an item that I must display its title as a <choice> in a <menu> while returning a different variable

I am working with an object: company: { name: 'Google', id: '123asd890jio345mcn', } My goal is to display the company name as an option in a material-ui selector (Autocomplete with TextField rendering). However, when a user selects ...