简体   繁体   English

当我们不知道Typescript中的属性名称时,以编程方式推送到类型为any的数组

[英]Programmatically pushing to an array of type any when we don't know the property names in Typescript

I created an Angular dropdown list component with an items property such as: items: any []; 我创建了一个带有item属性的Angular下拉列表组件,例如:items:any [];

The user of this component is able to set the items to an array of anything such as: 该组件的用户可以将项目设置为以下各项的数组:

[{id: "1", xyz: "hello"}, {id: "2", xyz: "world}] [{id:“ 1”,xyz:“ hello”},{id:“ 2”,xyz:“ world}]

or 要么

[{abc: "1", def: "john"}, {abc: "2", def: "doe"}] [{abc:“ 1”,def:“ john”},{abc:“ 2”,def:“ doe”}]

The user can additionally set the itemText and itemValue as two separate properties: 用户还可以将itemText和itemValue设置为两个单独的属性:

In the component they are declared as: 在组件中,它们声明为:

itemText: string; itemText:字符串;

itemValue: string; itemValue:字符串;

I am trying to create another set of properties called customItemtext and customItemValue. 我正在尝试创建另一组名为customItemtext和customItemValue的属性。 This will give the user the ability to add a custom option to the beginning of the items array that wasn't originally part of the datasource. 这将使用户能够向项目数组的开头添加自定义选项,而该选项本来不是数据源的一部分。 The problem here is that I would need to push the item without knowing the property names since they technically could be anything. 这里的问题是,我需要在不知道属性名称的情况下推送项目,因为从技术上讲它们可以是任何东西。

I was originally thinking to just get the property names from the itemText and itemValue properties but this isn't possible since the user can use formatting when setting the values of them. 我最初只是想从itemText和itemValue属性获取属性名称,但这是不可能的,因为用户可以在设置它们的值时使用格式。

Note: When the user sets the items array it comes directly from a query so the user has no flexibility in adding the custom items themselves. 注意:当用户设置items数组时,它直接来自查询,因此用户自己添加自定义项时没有灵活性。 It needs to be done by my component through properties. 这需要由我的组件通过属性来完成。

Wow I just built this: InputTagComponent 哇,我刚刚建造了这个: InputTagComponent

When you send the typeahead source it must be an array of objects. 发送预输入源时,它必须是对象数组。 Then, similar to yours, I use filterKeys = ['firstName','lastName'] and displayKeys = ['firstName'] . 然后,与您的相似,我使用filterKeys = ['firstName','lastName']displayKeys = ['firstName']

I don't allow users to send along a string when objects are being used. 使用对象时,我不允许用户发送字符串。 But you can! 但是你可以!

Here is how I'm adding user selected data to the form array: 这是我将用户选择的数据添加到表单数组的方法:

 addTag(value: any):void {
    // disallow blanks, duplicates, enforce maxTags limit and disallow string entries when displayKeys is set
    if (
      value == '' ||
      this.maxTags === this.tagsArray.length || 
      this.duplicates(value) || 
      (this.displayKeys !== null && typeof value === 'string')
    ) { return; }

    // if value is a string of comma-separated entries
    if (typeof value === 'string' && value.includes(',')) {
      for (let i = 0, j = value.split(",").length; i < j; i++) {
        this.tagsArray.push(new FormControl(value.split(",")[i]));
        this.onChange(this.tagsArray);
      }
      this.inputValue = '';
      this.float = true;
      return;
    }

    this.inputValue = '';
    this.float = true;
    this.tagsArray.push(new FormControl(value));
    this.onChange(this.tagsArray); // update controller value
  }

Removal is easy 拆卸很容易

  removeTag(i: number):void {
    this.tagsArray.removeAt(i);
    this.onChange(this.tagsArray); // update controller value
  }

Duplicate checks for objects are stringified, which also compares string input... 重复检查对象是否为字符串,也比较字符串输入...

  duplicates(value: any): boolean{
    const test = JSON.stringify(value);
    let match: boolean;

    // test for duplicate objects in tag array
    for ( let i = 0, j = this.tagsArray.value.length; i < j; i++ ) {
      let controlVal = JSON.stringify(this.tagsArray.value[i]);

      if (test === controlVal) { 
        return true;
      } else {
        match = false;
      }
    }
    return match;
  }

I hope this helps but please let me know if I can help more. 希望对您有所帮助,但请告诉我是否可以提供更多帮助。 Also FWIW I'm having an issue with this here is you have any insight: When is Angular's FormArray a traditional array and when is it a FormArray object? 另外,我对此有一个问题,您是否有任何见解: Angular的FormArray何时是传统数组,什么时候是FormArray对象?

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

相关问题 当我们不知道数据的嵌套级别时,如何在react / redux中的reducer state属性中更新数据? - How to update a data in a reducer state property in react/redux, when we don't know the level of nesting for the data? 我不知道打字稿中的返回类型 - I don't know about return type in typescript 在严格模式下编写脚本时,无法读取属性“ any”类型错误 - getting can't read property 'any' type error when we script in strict mode Javascript 如何循环一个 json 数组,我们不知道里面有多少嵌套数组? - Javascript how to loop over a json array where we don't know how many nested array there is inside? 通过推送更新类型为array的Backbone模型属性 - Update a Backbone model property of type array by pushing 推送到数组时,Typescript undefined不是对象 - Typescript undefined is not an object when pushing to array 推送数据时在TypeScript中键入数组 - Typing an Array in TypeScript when pushing data 以编程方式添加对象时如何从对象数组中键入属性 - How to type a property from an array of objects when adding them programmatically 是否可以在TypeScript中为属性名称定义类型 - Is it possible to define a type for property names in TypeScript TypeScript 条件类型和计算 object 属性名称 - TypeScript conditional type and computed object property names
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM