Khalid Emraan
Khalid Emraan

Reputation: 35

How to add a property to an object at a specific index of an array in typescript (Angular)?

emailData.contractors = [
                    0: {
                         id: 1,
                         email: asd@asd
                       }
                    1: {
                         id: 1,
                         email: asd@asd
                       }
                  ]
emailSub(event, data) {
    const trigger = $(event.target);
    this.emailData.contractors.forEach((v, i) => {
      if (v.id == data.id) {
        this.emailData.contractors[0]['subject'] = trigger.val();
      }
    });
  }

Expected Output

                    0: {
                         id: 1,
                         email: asd@asd
                         subject: 'sdf'
                       }
                    1: {
                         id: 1,
                         email: asd@asd`enter code here`
                       }
                  ]

How can i achive this in angular 8. the function above is not working on a keyup of an input from which i get the data

Upvotes: 1

Views: 989

Answers (2)

Adrita Sharma
Adrita Sharma

Reputation: 22213

Use Object.assign to add an property.

Try like this:

emailSub(event, data) {
   const trigger = $(event.target);
   let item = this.emailData.contractors.find(x => x.id == data.id);
   Object.assign(item, {'subject':trigger.val()})
}

Working Demo

Upvotes: 1

Dickens A S
Dickens A S

Reputation: 4054

change your data to

emailData.contractors = [
                {
                     id: 1,
                     email: "asd@asd"
                },
                {
                     id: 2,
                     email: "asd@asd"
                }
              ]

Or

emailData.contractors = {
                0: {
                     id: 1,
                     email: "asd@asd"
                },
                1: {
                     id: 2,
                     email: "asd@asd"
                }
              }

Upvotes: 0

Related Questions