Search code examples
javascripttypescriptobjectarrayobject

How to create a new property in a array object based on a condition in TypeScript


I have the below array object

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

I want to add a new property called "Flag" as 1 only if Age is greater than 15 in Typescript. I just wanted to know what are the ways we can create property for the above condition on the fly.

Sample Output,

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

Thanks in advance


Solution

  • You can make use of a pretty simple map, something like:

    const addFlagIfCond = (obj: {Name: string, Age: number}) => ({
      ...obj,
      ...(obj.Age > 15 ? { Flag: 1 } : {})
    })
    
    const newArr = arr.map(addFlagIfCond)