user2852270
user2852270

Reputation: 51

Value is duplicating

I'm working on angular. While trying to append a string to another string in array it is getting duplicated in second load. For example: I'm having a object

let exampleUser: ExampleUser[] = [{
  userId: 1,
  Name:'test'
  Desig: 'Manager',
  
}];

I'm trying to modify Name to Name + Desig. In first call it is working fine but in second call it is getting duplicated. I tried the below work around

exampleUser.forEach(e => e.Name= e.Name + " (" + e.Desig+ ")");

But on second call I'm getting the Name as 'test (Manager) (Manager)'. Can anyone please help me on this.

Upvotes: 0

Views: 32

Answers (1)

Pablo Aragon
Pablo Aragon

Reputation: 333

You have two options:

  1. create a new attribute in your object (for example NameDesig) and assign it the concatenated value:
let exampleUser: ExampleUser[] = [{
  userId: 1,
  Name:'test'
  Desig: 'Manager',
}];

exampleUser.forEach(e => e.NameDesig = e.Name + " (" + e.Desig+ ")");
  1. Don't mutate the original array but map it into a second array.
let exampleUser: ExampleUser[] = [{
  userId: 1,
  Name:'test'
  Desig: 'Manager',
}];

const exampleUser2 = exampleUser.map(e => ({
  ...e
  name: e.Name + " (" + e.Desig+ ")"
}));

Upvotes: 1

Related Questions