1

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.

Daniel
  • 3,541
  • 3
  • 33
  • 46
Raj
  • 65
  • 1
  • 2
  • 10

2 Answers2

2

This should work,

this.choices.push({id: 10,product: [{id:'5'}]});
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • I was trying to do the same but I added [] after push. Thank you so much. :) Bdw Is it possible to push these key-pair value at certain index? – Raj Aug 07 '17 at 16:56
  • yes you can https://stackoverflow.com/questions/586182/how-to-insert-an-item-into-an-array-at-a-specific-index – Sajeetharan Aug 07 '17 at 16:57
  • But it is for array. I want to do same for array of objects in the form of key value pairs. – Raj Aug 07 '17 at 17:00
  • As suggested by you, If i want to access "id" value with "Push" method: All i have to do is "choices[1].id " Right? Here index is "1" I want to change its index from 1 to some certain value lets say "10" – Raj Aug 07 '17 at 17:12
0

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.

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115