Is there a way to append a unique property with varying values to an array of objects in TypeScript?

For instance:

items: object[] = [
       {name: 'Backpack', weight: 2.5},
       {name: 'Flashlight', weight: 0.8},
       {name: 'Map', weight: 0.3}
      ];

I prefer the items to have an 'age' property as well:

itemList: object[] = [
       {name: 'Backpack', weight: 2.5, age: 10},
       {name: 'Flashlight', weight: 0.8, age: 15},
       {name: 'Map', weight: 0.3, age: 20}
      ]

I understand that I could iterate over each item and assign an age like this:

for(let i=0; i<items.length; i++){
  items[i].age = i * 5 + 10;
}

However, this method assigns ages in a linear sequence. Is there a more efficient way to achieve this?

Answer №1

Utilize a variable to store age values and increase it with each loop, in addition to using the spread operator:

let variable = 20;
this.inventory = this.inventory.map(item => {
  return {
    ...item,
    age: variable += 5,
  };
});

Furthermore, considering we are working with TypeScript, define an interface for representing inventory like so:

export interface Items {
  name: string;
  weight: number;
  age?: number;      // optional as it is updated later
}

Next, specify the array by using:

inventory: Items[] = [
  { name: 'Toolbox', weight: 2 },
  { name: 'Solar Panels', weight: 30 },
  { name: 'Medical Kit', weight: 10 },
  { name: 'Communication Device', weight: 5 },
];

Answer №2

My updated answer incorporates age as a randomly generated number falling between 20 and 60. Feel free to adjust the minimum and maximum values based on your needs.

equipment=[];
equipmentItems=[];

ngOnInit(){
  this.equipment= [
       {name: 'Duct Tape', mass: 0.5},
       {name: 'Space Camera', mass: 20},
       {name: 'Food', mass: 150},
       {name: 'Oxygen Tanks', mass: 400},
        ]; 

        this.equipmentItems=this.equipment;

        this.equipmentItems.forEach((arrayItem, index)=> {
        this.equipmentItems[index].age=this.generateRandomAge(20, 60);
       });
}

 generateRandomAge(min, max) {
  return Math.floor(min + Math.random()*(max + 1 - min))
}

See the code in action here: https://stackblitz.com/edit/angular-ivy-rjmdn1?file=src/app/app.component.html

If you want to generate random numbers without any limits:

this.equipmentItems.forEach((arrayItem, index)=> {
        this.equipmentItems[index].age=this.generateRandomAge(-20, 20);
       });

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

Trouble accessing images from database in Angular 2 with Firebase

Recently, I've integrated an image upload feature for my database using the following function: private saveFileData(upload: Upload): void { this.firebaseAuth.authState.subscribe(auth => { this.db.list(`uploads/${auth && auth.email && au ...

What methods exist for creating visual representations of data from a table without relying on plotting libraries?

Is there a way to plot graphs directly from a Data Table without the need for external graph libraries like plotly or highcharts? Ideally, I am looking for a solution similar to ag-grid where the functionality comes built-in without requiring manual code ...

I find that the value is consistently undefined whenever I attempt to set it within a promise in Angular

Hi there, I've encountered an issue with my getData() function in accountService.ts. I'm attempting to fetch user data and user account data simultaneously using a zip promise. Although the resolve works correctly and I receive the accurate data, ...

When attempting to print a Rectangle on my webpage using JavaScript and taking user input, I encountered an error stating that 'str' is not defined

I'm trying to implement a feature where clicking on the "try it" button will prompt the user for the number of lines and then print that many lines in the form of a rectangle. However, when I run my code, nothing appears on the DOM and there is an err ...

Having issues with creating a new project using 'ng new hello-world' and also not able to resolve

I encountered an error while attempting to create a new app and even after trying ‘ng cache clean --force’, the issue persists. I attempted to reinstall node.js, npm, and angular-cli but none of these solutions proved effective for me. It may appear ...

Encountering issues with Angular2 App when attempting to load simulated data using a Promise causes malfunction

Looking to implement my mocked data loading using a promise, similar to the approach shown in the Angular2 Tutorial found here. Service (Mock): import { Injectable } from '@angular/core'; import { ERGEBNISSE } from "./mock-ergebnisse"; @Inject ...

convert a JSON object into an array field

I am looking to convert a list of objects with the following structure: { "idActivite": 1, "nomActivite": "Accueil des participants autour d’un café viennoiseries", "descriptionActivite": "", "lieuActivite": "", "typeActivite": "", ...

Achieving dynamic serving of static files using Rollup and integrating seamlessly with node-resolve

Currently, I am in the process of building a library using TSDX, which is a powerful CLI tool for package development based on Rollup. My project involves a collection of country flags SVGs that need to be imported and displayed dynamically when required. ...

Displaying svg files conditionally in a react native application

I have developed an app specifically for trading dogs. Each dog breed in my app is associated with its own unique svg file, which are all stored in the assets folder (approximately 150 svg files in total). When retrieving post data from the backend, I re ...

Encountering issue with POST operation in GraphQL on Angular application integrated with AWS Amplify and DynamoDB

I am in the process of developing a basic Angular application using AWS Amplify with a DynamoDB backend. To handle GraphQL API calls, I utilized the amplify add API command to generate the necessary code. My current objective is to populate a table with ...

Stylesheets per module in Angular 2

For my website design, I've decided to adopt a modular structure using sass. To ensure consistency throughout the module, instead of defining stylesheets at the component level, I plan to define them at the module level and import them into each compo ...

Issue with Nativescript Angular router version 3.0.0-alpha.7 causing navigation errors

This project example highlights a problem: https://github.com/rrcoolp/test-router-app/ Issue with navigation: The test project showcases an issue with NATIVESCRIPT ANGULAR 2 (RC3) and Nativescript router 3.0.0-alpha.7. The problem is straightforward - na ...

Sending user input data from a React text field to a function as arguments

Below are input fields, from which I need to retrieve the entered values and pass them to the onClick event of the button displayed below. <input type="text" style={textFieldStyle} name="topicBox" placeholder="Enter topic here..."/> <input type=" ...

Issue with Moment.js: inability to append hours and minutes to a designated time

I have a starting time and I need to add an ending time to it. For example: start=19:09 end=00:51 // 0 hours and 51 minutes I want to add the 51 minutes to the 19:09 to make it 20:00. I've attempted several different methods as shown below, but none ...

What could be the reason for JSON refusing to accept an element from an array?

I am looking to retrieve the exchange rates for all currencies from an API using an array that lists all available currencies. Below is the JavaScript code I have written: var requestURL = 'https://api.fixer.io/latest'; var requestUrlstandard ...

Refreshing Datatable in Angular 2 - Trouble with dtInstance.then error

I'm currently working on an Angular 2 application where I have a component that includes both a dropdown list and a datatable. The requirement is to display details in the table based on the name selected from the dropdown list. HTML - <div> ...

Accessing identical values from various arrays

I have two arrays, each containing 3 values. I need to randomly select 2 values from each array. For example, selecting "red" and "blue" from array 1, and "red" and "blue" from array 2. The goal is to randomly match the keys from both arrays and change the ...

Angujar2, could you provide guidance on how to extract components from a string?

Hey Angujar2, is there a way to interpret a component in string format? I need help with the test component (director). The section we are focusing on is app-test. Here's the main component in HTML: <app-test>text</app-test> I am look ...

What is the best way to connect my Angular 2 project to the "$wakanda" service in order to access and retrieve data efficiently?

Recently, I started a new project on the wakanda.io platform using angular2 and backend technologies. After creating some database entities, I now need to retrieve data from the database on the client side. To do this, I am looking for a way to import the ...

Unveiling RxJs: The secret to extracting the notifier value using the takeuntil operator

I have a straightforward Rxjs timer set up that runs until a notifier emits a signal, it's pretty basic so far. enum TimerResult = { COMPLETE, ABORTED, SKIPPED }; _notifier: Subject<TimerResult> = new Subject(); notifier$: Observab ...