Add a new literal object to an object array!

Asked

Viewed 3,399 times

-2

I would like to add a new item to my object array through a method, but I don’t know how to do it.

public products: Array<Object> = [
  {prodName: 'product 1', prodElement: 'element 1', prodAttribute: 'Attribute 1', attrValue: 'value 1'},
];
  • 2

    Leonardo, if you don’t know how to add a new element to an array, I don’t think you should be messing with Angular. Learn pure Javascript (Vanilla) first then leave for some framework. Just a tip!

  • i didn’t know how to add an object inside an array. But I know the methods of an array. I’m an intern bro, but thanks for the tip

2 answers

3

products is receiving an array, within the array we have the property . push to add and . splice to remove, . push vc passes only one object or any type of primary that is in the array, in the splice vc passes the index and as the second parameter the number of indexes to be removed.

products.splice(indexOf, 'itens a serem retirados a partir do index')
products.push({Objeto da forma como vc quiser inserir})

As Javascript is weakly typed, no problem vc declare the way:

var products = [];

Creating your objects inside.

products.push({'nome':'Sérgio', 'idade':23, 'profissao':'programador angularjs}')
  • Is push() not push[].

1

The push increments a new item to your array:

this.products.push({prodName: 'product 1'});

Maybe you have to declare it that way to work:

public products: any = [{prodName: 'product 1'}];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.