简体   繁体   English

如何根据 TypeScript 中的条件在数组对象中创建新属性

[英]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.仅当 Typescript 中的 Age 大于 15 时,我才想添加一个名为“Flag”的新属性为 1。 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提前致谢

Since it's typescript i'll create a type for my array and do something like this :由于它是打字稿,我将为我的数组创建一个类型并执行如下操作:

type Array = { Name: string; Age: number; Flag?: 1 | 0 }[];
let arr: Array = [
  { Name: "ABC", Age: 20 },
  { Name: "XXX", Age: 15 }
];
arr.map(element => {
  if (element.Age > 15) {
    element.Flag = 1;
  }
});

console.log(arr);

You can change the type of Flag as you wish.您可以根据需要更改标志的类型。 It can be boolean, number or a defined set as i did.它可以是布尔值、数字或像我一样的定义集。

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)

Use a class instead of a plain object, and overload the getter for the flag to generate it on the fly.使用类而不是普通对象,并重载标志的 getter 以动态生成它。

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

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

const person: Person = new Person('Johnny', 6);
console.log(person.flag);
// outputs 0

person.age = 20;
console.log(person.flag);
// outputs 1

Use map to modify the array.使用map修改数组。

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

This is your array of objects这是你的对象数组

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

For loop for the apply condition to all objects将应用条件应用于所有对象的 For 循环

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

It can be done on compile time if you precisely define Age type.如果您精确定义Age类型,则可以在编译时完成。 A lot of typing but you got full check on the type level.打字很多,但您对类型级别进行了全面检查。

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 to 100 :)


// definition of two possible versions of our 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM