How to push object into an array? in Angular 7

Mark picture Mark · Jul 12, 2019 · Viewed 21.2k times · Source

I am pushing an object into an array but cannot do it?

I'm doing it like this

this.passData = this.tribeForm.value;
    var id = {"tribe_id": 1}
    this.passData.push(id)

This is the value in the tribeForm

enter image description here

I also tried

var id = {tribe_id: 1}

and

this.passData.splice(0,0, id)

and

this.passData = Array.prototype.slice(id)

and

this.passData.concat(id)

but it all ends up with

TypeError: this.passData.push/splice/concat is not a function

Answer

Narasimha Prasanna HN picture Narasimha Prasanna HN · Jul 12, 2019

The question is not that clear, But I understood you are manipulating form data, value of form data returns an Object, Not an array. Objects in JavaScript are represented as key-value pairs, (or attribute-value) pairs.

Example :

var object = {
  name : "Jhon", 
  grade : 12,
  gpa : 8.12
}

It is just a collection of key-value pairs, push(), concat() and other methods are supported only for Arrays not for Objects. You can achieve whatever you want simply by creating a new key/attribute and assigning the value to it.

this.passData = this.tribeForm.value
this.passData['tribe_id'] = 1
//or, Objects can also contain nested object
this.passData['someKey'] = {'tribe_id' : 1} 

You can create an empty array and push objects to it

Example :

var exampleArray = []
exampleArray.push({'tribe_id' : 1})

Now, it works because exampleArray is an Array not JS object.

Thanks for A2A