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
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)