0

I have an angular project where I have a block of code that returns an array of objects, which consists of contact records.

I have a 'forEach' loop where I create a new field with the user's initials.

I want to then push this new field 'userInitials' into the appropriate record.

I have the following code, but it's pushing new objects and not new fields, but when I remove the object brackets, I get errors.

    let initialHold: any;
    let contactWithInitials = [];

    this.contacts.forEach( eachObj => {
      if(eachObj.first_name){
        initialHold = eachObj.first_name.charAt(0);
      }
      if(eachObj.last_name){
        initialHold += eachObj.last_name.charAt(0);
      }

      this.contacts.push({'userInitials':initialHold});

    })

1 Answer 1

2

Use this eachObj['userInitials'] = initialHold instead of this.contacts.push({'userInitials':initialHold});. You want to mutate the original object, then you have to add the new property to the eachObj once you create the new property.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.