简体   繁体   English

访问 Typescript 中的 object 内的数组

[英]Accessing array inside an object in Typescript

I am having an Array called Entites, in which i have an object that contains "title", "category" and an array feedbacks.我有一个名为 Entites 的数组,其中我有一个 object,其中包含“标题”、“类别”和数组反馈。

createEntity(title:string,catgory:category){
        if(this.m_role=="Admin"){
          var obj ={"title":title,
                    "category":catgory,
                    feedbacks:['hello']
        };
         this.Entites.push(obj);
        }else{
            console.log("You need to be an Admin to create Entity.");
        }
    }

What i want to do is i want to push into this feedback array.我想做的是我想推入这个反馈数组。 I am trying this我正在尝试这个

//writeFeedback[User]
    writeFeedback(feed:string,titleOfEntity:string){
        if(this.m_role=="User"){
            const to_edit=this.Entites.indexOf({"title":titleOfEntity});
            this.Entites[to_edit].feedbacks.push('Added Feedback');
        }
    }

But this doesn't work.但这不起作用。 On logging 'to_edit' I get -1.在记录“to_edit”时,我得到-1。 What am I doing wrong?我究竟做错了什么? I get this error message on the compilation我在编译时收到此错误消息

Property 'feedbacks' does not exist on type 'object'

You can use Array.prototype.map for that:您可以为此使用Array.prototype.map

  writeFeedback(feed: string, titleOfEntity: string) {
    if (this.m_role == 'User') {
      this.Entites = this.Entites.map((ent) =>
        ent.title === titleOfEntity
          ? { ...ent, feedbacks: [...ent.feedbacks, 'Added Feedback'] }
          : ent
      );
    }
  }

Update:更新:

Property 'feedbacks' does not exist on type 'object'

If you have an interface for entities then add feedbacks to that or create a new interface.如果您有entities接口,则向该接口添加feedbacks或创建新接口。

interface Entity {
    title: string;
    category: Category;
    feedbacks: string[];
}

// inside the class
Entities: Entity[]

To obtain a matching item within an array use map() and indexOf().要在数组中获取匹配项,请使用 map() 和 indexOf()。 Then check the index before updating the indexed array item:然后在更新索引数组项之前检查索引:

const to_edit=this.Entites.map(e => 
   e['title']).indexOf(titleOfEntity);

if (to_edit > -1)        
    this.Entites[to_edit].feedbacks.push('Added Feedback');

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

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