admin管理员组

文章数量:1405880

I have defined array of object something like this:

  this.choices =  [
        {
            id: 0,
            product: [{id:'0'}] 
        }
        ];

Now I want to insert new key-value pair in choices :

                    [
                    {
                        id: 10,
                        product: [{id:'5'}] 
                    }
                    ]

I tried to do it by push() method but I guess its for Array only. Please help me with same. Thank you so much in advance. :) Also, Is it possible to push these key-pair value at certain index for these array of objects.

I have defined array of object something like this:

  this.choices =  [
        {
            id: 0,
            product: [{id:'0'}] 
        }
        ];

Now I want to insert new key-value pair in choices :

                    [
                    {
                        id: 10,
                        product: [{id:'5'}] 
                    }
                    ]

I tried to do it by push() method but I guess its for Array only. Please help me with same. Thank you so much in advance. :) Also, Is it possible to push these key-pair value at certain index for these array of objects.

Share edited Aug 7, 2017 at 17:09 Daniel 3,5143 gold badges36 silver badges47 bronze badges asked Aug 7, 2017 at 16:46 RajRaj 651 gold badge3 silver badges11 bronze badges 2
  • how did you try with push? – tlt Commented Aug 7, 2017 at 16:49
  • I did something like this : this.choices.push( [ { id: '10', product: [{id:'5'}] , } ]); } I guess extra square bracket was causing problem. – Raj Commented Aug 7, 2017 at 17:01
Add a ment  | 

2 Answers 2

Reset to default 2

This should work,

this.choices.push({id: 10,product: [{id:'5'}]});

Since both examples are actually arrays containing objects, you should be using concat rather than push. ie;

this.choices =  [
        {
            id: 0,
            product: [{id:'0'}] 
        }
        ];


var newVal =  [
                    {
                        id: 10,
                        product: [{id:'5'}] 
                    }
                    ];


this.choices = this.choices.concat(newVal);

In my example, to use push you'd need to do this.choices.push(newVal[0]) - many ways to approach it but basically, push is for individual values, concat is for arrays.

本文标签: arraysHow to push new key value pair in existing javascript objectStack Overflow