-1

Trying to add new object value in an array but not working. How to add it? If anyone knows please help to find the solution.

getting this error:

Property 'includes' does not exist on type '{ name: string; id: string; }[]'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2016' or later.

app.component.ts:

public a = { name: 'test1', id: '12345' };
public b = { name: 'test2', id: '12345' };

addVala() {
  if (this.arr.includes(this.a)) {
    console.log('This obj already there');
  } else {
    this.arr.push(this.a);
  }
  console.log(this.arr);
}

Demo : https://stackblitz.com/edit/angular-ivy-jj7sna?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.ts

EMahan K
  • 417
  • 1
  • 19

1 Answers1

1

You can simplify your "add" logic by passing-in the object that you want to add and checking if another object (already in the list) shares the same ID.

const arr = [
  { name: 'test1', id: 'A' },
  { name: 'test3', id: 'C' },
];
  
const a = { name: 'test1', id: 'A' };
const b = { name: 'test2', id: 'B' };

const add = (obj) => {
  if (!arr.find(({ id }) => id === obj.id)) {
    arr.push(obj);
    console.log(`Added ${obj.id}`);
  } else {
    console.log(`Object ${obj.id} already exists!`);
  }
}

function addA() { add(a); }
function addB() { add(b); }
<button onclick="addA()">Add A</button>
<button onclick="addB()">Add B</button>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132