Tips for adding a new property to an array object in TypeScript using a condition

Here is an array object that I have:

 arr = [
   { Name: "ABC", Age: 20},
   { Name: "XXX", Age: 15}
 ];

In Typescript, I am looking to dynamically add a new property called "Flag" with a value of 1 only if the Age is greater than 15. Can someone suggest various methods to achieve this condition on the fly?

Expected Output,

arr = [
   { Name: "ABC", Age: 20, Flag: 1},
   { Name: "XXX", Age: 15}
 ];

Appreciate any help in advance!

Answer №1

If you're looking to enhance your data with a flag based on a condition, consider implementing a basic mapping function like the one below:

const addFlagIfCondition = (object: {Name: string, Age: number}) => ({
  ...object,
  ...(object.Age > 15 ? { Flag: 1 } : {})
})

const updatedArray = originalArray.map(addFlagIfCondition)

Answer №2

When dealing with typescript, I typically define a type for my array and approach it like this:

type MyArray = { Title: string; Number: number; Active?: 1 | 0 }[];
let myList: MyArray = [
  { Title: "Apple", Number: 50 },
  { Title: "Banana", Number: 30 }
];
myList.map(item => {
  if (item.Number > 35) {
    item.Active = 1;
  }
});

console.log(myList);

You have the flexibility to adjust the type of Active based on your needs, whether it's boolean, numeric, or a specific set as shown above.

Answer №3

Implement changes to the array using the map method.

arr.map(item => { 
  if(item.Age > 15) {
    item.Flag = 1;
  }
});

Answer №4

To improve the code, utilize a class instead of a plain object and create an overloaded getter method for the flag to generate it dynamically.

class Person {
    constructor(public name: string, public age: number) {}

    get flag() {
        return this.age > 15 ? 1 : 0;
    } 
}

const person: Person = new Person('Sarah', 12);
console.log(person.flag);
// prints 0

person.age = 18;
console.log(person.flag);
// prints 1

Answer №5

Here is an example of your array filled with objects:

    let data = [
       { Name: "John", Age: 25},
      { Name: "Jane", Age: 30}
    ];

Using a for loop to check and apply a condition to each object in the array:

    for(let i=0; i<data.length; i++)
    {
      if(data[i].Age > 20)
        data[i]["Flag"]=1;
    }

Answer №6

To achieve compilation at compile time, one must meticulously define the Age type. Although it requires a significant amount of typing, it provides complete type-level verification.

type AgeTo15 = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15;
type AgeAbove15 = 15 | 16 | 17 | 18 | 19 | 20 | 21; // and so on up to 100 :)


// defining two versions of our custom data type
type To15Data = {
    Name: string,
    Age: AgeTo15,
}

type Above15Data = {
    Name: string,
    Age: AgeAbove15,
    Flag: number,
}

type Data = To15Data | Above15Data;

const el: Data = {
    Name: 'Name',
    Age: 10, 
} // valid

const el2: Data = {
    Name: 'Name',
    Age: 20, 
} // invalid

const el3: Data = {
    Name: 'Name',
    Age: 20, 
    Flag: 1
} // valid


const arr: Data[] = [
   { Name: "ABC", Age: 20},
   { Name: "XXX", Age: 15}
 ]; // invalid

const arr2: Data[] = [
   { Name: "ABC", Age: 20, Flag: 1},
   { Name: "XXX", Age: 15}
 ]; // valid

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

Provide a random number that is not already listed in the array

I am working on creating a function that accepts an array as input, generates a random number between 1 and 10, keeps generating numbers until it finds one that is not in the array, and then returns that number. For more information and to see the code in ...

Prevent special characters in input fields using Angular and TypeScript

I am currently working on an Angular project using Ant Design ng Zorro. I've encountered an issue with validation when trying to restrict special characters in an input field. Despite setting up the validation rules, it seems that the key press event ...

Is it a scope issue if ng-click is not firing and the function is not working properly?

I'm facing an issue with an animation that is not working as intended. The goal is to have the search button trigger an animation to pull a search bar from the right side, allowing users to input their search query. However, the ng-click function does ...

"Utilizing the `useState` function within a `Pressable

Experiencing some unusual behavior that I can't quite figure out. I have a basic form with a submit button, and as I type into the input boxes, I can see the state updating correctly. However, when I click the button, it seems to come out as reset. Th ...

Enhance your Next.js application by including the 'style' attribute to an element within an event listener

I am currently trying to add styles to a DOM element in Next.js using TypeScript. However, I keep getting the error message "Property 'style' does not exist on type 'Element'" in Visual Studio Code. I have been unable to find an answer ...

Setting up user roles using Firebase Auth in NextJS application

Seeking a solution to implement a multi-level role system for my blog website. Currently utilizing Firebase Auth for authentication with email/password, but all users have the same posting/editing access. Looking to differentiate between Admins, Moderators ...

The function 'compilation.emitAsset' is not recognized by the sitemap-webpack-plugin

I'm currently working on setting up a sitemap for my live environment and I've encountered an issue while trying to utilize the sitemap-webpack-plugin. The error message I received is as follows: ERROR in TypeError: compilation.emitAsset is not a ...

Type of tuple without a specific order

Exploring Typescript typings has led me to ponder how to create a type that is a tuple with unordered element types. For example: type SimpleTuple = [number, string]; const tup1: SimpleTuple = [7, `7`]; // Valid const tup2: SimpleTuple = [`7`, 7]; // &ap ...

Delivering create-react-app's build files through an express server

I am trying to serve the build files of my React app on another Express application. I have copied all the static files from the build folder to the public folder inside my Express application and have set up the following code: app.use(express.static(pat ...

Node.js 0.12 now offers access to the latest ECMAScript 6 features

The latest version of Node.js (0.12) has been released with an updated Google's v8 JavaScript engine, v3.28.73. Which ECMAScript 6 features are currently available in Node.js without using the --harmony flag? I have searched multiple websites that c ...

Is there a way to restrict keyboard input on this date picker?

Can you review the following link and let me know which properties or events I should utilize in this scenario? https://codesandbox.io/s/charming-frost-qrvwe?file=/src/App.js ...

Sending a JavaScript string to a PHP script from a Chrome extension content script

I am currently developing a chrome extension that is designed to extract text data from specific websites when I visit them, and then store this data in a SQL database. The JavaScript code for data extraction is functioning correctly and is able to capture ...

Insufficient allocation - memory overflow in loopback.js

I encountered an issue while trying to fetch large data using loopback.js. The error message I received was: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory <--- Last few GCs ---> 45903 ms: Mark-sweep 1385.6 (14 ...

Dividing the logic from the Express router while retaining the ability to utilize Express functionalities

As I embark on my journey of developing my first app using Node.js and Express, I have noticed that my router file is starting to get overcrowded with logic. It seems like there is too much going on in there. My solution to this issue is to pass a functio ...

The problem of removing issue divs persists despite Jquery's efforts

Just yesterday, I successfully created a Commentbox using PHP, HTML, and ajax. The beauty of the ajax part is that it allows me to delete a comment without having to refresh the page. To achieve this, I assign a unique id to each comment (div) through the ...

Is there a way to display multiple images in a JSON message object?

If you're looking for a fun way to generate random dog images, then check out my DogAPI image generator! Simply enter a number between 1-50 into the form text box, hit send, and watch as it displays that amount of random dog photos. I'm almost t ...

How to turn off automatic formatting in CKEditor

Whenever data is entered into a field using CKEditor, the Save button becomes enabled. However, if I programmatically set data into the field using Javascript, the Change event always triggers causing the Save button to remain enabled even if the field is ...

Combining Various Items Retrieved from Fetch Request

I am attempting to merge multiple objects retrieved from an API by grouping them based on their id and values, ensuring that any modifications are only applied to individual objects rather than affecting all of them. Here is my latest approach: const car ...

Can you explain the concept of themes in Material UI?

I am trying to wrap my head around the concept of themes and what they are meant to represent. I have gone through the documentation, but I still find it confusing. For instance, here is a snippet of code that I am referring to. I just want to understand ...

Tips for creating a useState variable within the render() function in reactjs

I'm completely new to reactjs, and I've been trying to define useState variables within the render() method of a reactjs component. However, I keep running into an error: "Invalid hook call." class ProductDefinition extends Component { construc ...