Mark
Mark

Reputation: 313

How to push object into an array? in Angular 7

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

Upvotes: 3

Views: 67186

Answers (3)

Avtandil Kavrelishvili
Avtandil Kavrelishvili

Reputation: 1757

This is a simple answer with multiply object case too.

      this.passData.push({ tribe_id: 1, name: "lorm ipsum" });

Upvotes: 0

Ethan Vu
Ethan Vu

Reputation: 2987

First, you need to understand the error:

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

Push/splice/concat is functions for Array and because of that the console is yelling at you that the passData is not an Array.

Make sure your passData is an Array and you will able to do so.

Upvotes: 2

Narasimha Prasanna HN
Narasimha Prasanna HN

Reputation: 662

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

Upvotes: 3

Related Questions