Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an object to an array of objects with splice

Tags:

javascript

I have an array of objects that looks like this:

event_id=[{"0":"e1"},{"0","e2"},{"0","e4"}];

How do I add an element to that array?

I thought of

event_id.splice(1,0,{"0":"e5"});

Thanks.

like image 868
user823527 Avatar asked Mar 30 '12 16:03

user823527


1 Answers

If you just want to add a value to the end of an array then the push(newObj) function is easiest, although splice(...) will also work (just a bit trickier).

var event_id = [{"0":"e1"}, {"0":"e2"}, {"0":"e4"}];
event_id.push({"0":"e5"});
//event_id.splice(event_id.length, 0, {"0":"e5"}); // Same as above.
//event_id[event_id.length] = {"0":"e5"}; // Also the same.
event_id; // => [{"0":"e1"}, {"0":"e2"}, {"0":"e4"}, {"0":"e5"}]; 

See the excellent MDN documentation for the Array object for a good reference of the methods and properties available on arrays.

[Edit] To insert something into the middle of the array then you'll definitely want to use the splice(index, numToDelete, el1, el2, ..., eln) method which handles both deleting and inserting arbitrary elements at any position:

var a  = ['a', 'b', 'e'];
a.splice( 2,   // At index 2 (where the 'e' is),
          0,   // delete zero elements,
         'c',  // and insert the element 'c',
         'd'); // and the element 'd'.
a; // => ['a', 'b', 'c', 'd', 'e']
like image 88
maerics Avatar answered Sep 19 '22 15:09

maerics