3

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
3
  • 1
    tribeForm is not an array, it's an object. You can not push/concat/slice an object. What instead you can do is this.passData['id']=id Commented Jul 12, 2019 at 4:03
  • can you show this.passData value Commented Jul 12, 2019 at 4:11
  • if (!this.passData) this.passData=[id] else this.passData.push(id). NOTE: in typescript not use var, use let or constant Commented Jul 12, 2019 at 6:15

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

This is a simple answer with multiply object case too.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.