Reputation: 121
I am using the .data() function in jQuery to store an array as per below:
var myArray = {};
myArray[0] = {};
myArray[0][0] = "test00";
myArray[0][1] = "test01";
myArray[1] = {};
myArray[1][0] = "test10";
myArray[1][1] = "test11";
$('#datastorage').data("testname". myArray);
I want to remove only one item (myArray[0]) from the "testname" and keep the rest.
The below does not work:
$('#datastorage').removeData("testname").removeData(0);
I believe jQuery stored the array in a form of a plain object (the test $.isPlainObject()
comes back true)
I am now trying to use the function .not()
to remove the element...
Upvotes: 0
Views: 2245
Reputation: 340045
Since the original object is an array, what's actually stored is just a reference to the original data, so any modification you make is reflected in every reference to that array, including the one stored in .data()
.
So you can just remove the element from the array:
$('#datastorage').data("testname").shift();
or if you want more flexibility on which elements are removed, use .splice()
.
$('#datastorage').data("testname").splice(0, 1);
or if you've still got access to myArray
:
myArray.shift();
There's no need to put the array back into .data()
- any of the above will modify both myArray
and whatever's already in .data()
- they're the same array!.
The same would apply if the data was an object, but not if it's a primitive type.
Upvotes: 3
Reputation: 123428
try this code
var myArray = []; // myArray is an Array, not an object
myArray[0] = {};
myArray[0][0] = "test00";
myArray[0][1] = "test01";
myArray[1] = {};
myArray[1][0] = "test10";
myArray[1][1] = "test11";
$('#datastorage').data("testname", myArray);
console.log($('#datastorage').data("testname"));
$('#datastorage').data("testname", myArray.slice(1));
console.log($('#datastorage').data("testname"));
example fiddle: http://jsfiddle.net/nNg68/
Upvotes: 0
Reputation: 7253
You'll have to get the array out, remove from it, and then put it back.
var a = $('#datastorage').data('testname');
a.splice(0,1); // remove 1 item from position 0
$('#datastorage').data('testname', a);
Upvotes: 0