I was curious about adding elements in to an associative array using javascript,
var text=[{"key":"1", "value":"no"},{"key":"2", "value":"yes"} ];
what if I want to add an element in to above array… say to second location,
text[1].key="4";
text[1].value="test";
I ve tried it this way,
test.splice(parseInt(1), 0 );
test[1].type="4";
test[1].value="test";
Here’s some example code (with which you can play around here):
The
array.splice()method takes the following parameters (taken from here):index: An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array.howmany: The number of items to be removed. If set to 0, no items will be removed.itemN: The new item(s) to be added to the array.EDIT
To remove an element from the array you can use the same
splicefunction in the following way:Here we are indicating to
spliceat position1, remove1element but since we are not providing any elements to insert, none is inserted, which results in a single element at position1removed.