jQuery .data() remove item from stored array - javascript

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...

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.

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);

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/

Related

push Object in array in $.each

Maybe I'm just blind, but I'm struggling for a good amount of time now:
I have a small piece of JS-Code here:
var linkInput = $('#Link input.gwt-TextBox').val();
var parentRow = $('#Link').parent().parent();
var links = linkInput.split("|");
// hide text-input
$(parentRow).hide();
// get rid of empty elements
links = links.filter(Boolean);
var aSites = [];
var oSite = {};
$(links).each(function (k, v) {
splits = v.split(".");
domainName = splits[1];
oSite.name = domainName;
oSite.url = v;
aSites.push(oSite);
});
console.log(aSites);
To specify: Get the value of an input-field, hide the row afterwards and save all the values in an object, which is then pushed into an array.
The parameter, taken from the console-tab of google Chrome:
var links = ["www.myshop1.de/article/1021581", "https://www.myshop2.de/article/1021581"] [type: object]
I thought, I iterate through all elements of this object (in that case 2 times), push the values into an object and the object into an array, to have access to all of them afterwards.
At some point however, I seem to override my former values, since my output looks like this:
0: {name: "myshop1", url: "https://www.myshop1.de/1021581"}
1: {name: "myshop2", url: "https://www.myshop2.de/1021581"}
length: 2
__proto__: Array(0)
Where is my mistake here? Is there a smarter way to realize this?
On a sidenote:
I tried to use only an array (without adding an object), but it seems like I
can't use an associative key like this:
var myKey = "foo";
var myValue = "bar";
myArray[myKey] = myValue
You should move this:
var oSite = {};
...inside the each callback below it, because you need a new object in each iteration.
Otherwise you are mutating the same object again and again, pushing the same object repeatedly to the aSites array, which ends up with multiple references to the same object.
Not related, but you can use $.map to create your array (or vanilla JS links.map()):
var aSites = $.map(links, function(v) {
return { name: v.split(".")[1], url: v };
});

pass array to method with condition

Im using the following code to split array which is working,
I need to pass some value when array
for examle here is split the value to array
var myArr = val.split(/(\s+)/);
and if array in place 2 is empty I need to use the method like following
pass empty array in second arg
var val = process.run(myArr[0], [], options);
if the array place 2 is not empty I need to pass it like following
var val = process.run(myArr[0], [myArr[2]], options);
The second arg is array inside arry with the value of 2
there is nice way to do it instead of if on the method ?
I would create a function, as Dave Newton recommends. I could take the initial val and options as an argument and return the result of process.run:
function runProcess(val, options) {
var myArr = val.split(/(\s+)/);
var argArray = [];
if(myArr[2]) {
argArray.push(myArr[2]);
}
return process.run(myArr[0], argArray, options);
}
Since I don't know what the function exactly does, the name of the function and variables are pretty arbitrary. Feel free to change them to your needs.
If myArr[2] is a flat array and will always be flat, why not...
var val = process.run(myArr[0], [].concat(myArr[2]), options);

JavaScript Two dimensional Array

I am creating javascript two dimensional array
code is :
var field_arr=[];
$(".dr").each(function(index){
Id=$(this).attr("id");
alert(dragId);
topPos=$("#"+ dragId).position().top;
left=$("#"+ dragId).position().left;
parentDiv=$("#"+dragId).parent().attr("id");
parentDiv= parentDiv.split('-');
paId=parentDiv[1];
field_arr[Id]=new Array();
field_arr[Id]['paId']=paId;
field_arr[Id]['top']=topPos;
field_arr[Id]['left']=left;
});
console.log(field_arr);
Output Is:
[undefined, [] left 140 paId "1" top 10
What is problem in It Any help Should be appreciated.
The problem is in the display method of your arrays. The information is there, but both alert and console.log will not show it to you because it is expected that the only interesting properties of arrays are the ones with numeric indexes.
In JavaScript, unlike PHP, objects are used as maps/associative arrays.
First to check that your information is actually there:
$(".dr").each(function(index){
var Id=$(this).attr("id");
console.log(Id, field_arr[Id]['paId'], field_arr[Id]['top'], field_arr[Id]['left']);
});
Now to make make the display methods work you can go about multiple ways, but the best one is to use objects instead:
var field_arr = Object.create(null); // replace with {} if you want to support IE8-
$(".dr").each(function(index){
var id = $(this).attr("id"); // added var to keep variable local
var drag = $("#"+dragId);
field_arr[id] = Object.create(null); // {}
field_arr[id]['paId'] = drag.parent().attr("id").split('-')[1];
field_arr[id]['top'] = drag.position().top;
field_arr[id]['left'] = drag.position().left;
});
console.log(field_arr);
Iterating over properties of objects is quite easy:
for (var id in field_arr) {
console.log(field_arr[id], field_arr[id]['paId'], 'etc');
}
Add a hasOwnProperty check if your object doesn't inherit from null (var obj = {} needs it, unlike var obj = Object.create(null))
you're storing values with a key string and its wrong because you declared your field_arr as a numerical array (well there's no such thing as associative array in javascript i think).
field_arr[Id] = new Array();
field_arr[Id]['paId']=paId; //this is wrong
You need to create an object to store in values as if they are associated with string keys. But literally they are object properties
redeclare it like this
field_arr[Id] = {}; //you create an object
field_arr[Id]['paId'] = paId; //create an object property named paId and store a value
field_arr[Id].paId = paId; //you can also access property paId like this
EDIT:
but to conform to you current code you can access your indexes using strings by accessing it like a property of an object. (Thanks to Tibos)
var field_arr=[];
...
...
field_arr[Id].paId = paId;

Difference between Array.length = 0 and Array =[]?

Can some one explain the conceptual difference between both of them. Read somewhere that the second one creates a new array by destroying all references to the existing array and the .length=0 just empties the array. But it didn't work in my case
//Declaration
var arr = new Array();
The below one is the looping code that executes again and again.
$("#dummy").load("something.php",function(){
arr.length =0;// expected to empty the array
$("div").each(function(){
arr = arr + $(this).html();
});
});
But if I replace the code with arr =[] in place of arr.length=0 it works fine. Can anyone explain what's happening here.
foo = [] creates a new array and assigns a reference to it to a variable. Any other references are unaffected and still point to the original array.
foo.length = 0 modifies the array itself. If you access it via a different variable, then you still get the modified array.
Read somewhere that the second one creates a new array by destroying all references to the existing array
That is backwards. It creates a new array and doesn't destroy other references.
var foo = [1,2,3];
var bar = [1,2,3];
var foo2 = foo;
var bar2 = bar;
foo = [];
bar.length = 0;
console.log(foo, bar, foo2, bar2);
gives:
[] [] [1, 2, 3] []
arr.length =0;// expected to empty the array
and it does empty the array, at least the first time. After the first time you do this:
arr = arr + $(this).html();
… which overwrites the array with a string.
The length property of a string is read-only, so assigning 0 to it has no effect.
The difference here is best demonstrated in the following example:
var arrayA = [1,2,3,4,5];
function clearUsingLength (ar) {
ar.length = 0;
}
function clearByOverwriting(ar) {
ar = [];
}
alert("Original Length: " + arrayA.length);
clearByOverwriting(arrayA);
alert("After Overwriting: " + arrayA.length);
clearUsingLength(arrayA);
alert("After Using Length: " + arrayA.length);
Of which a live demo can be seen here: http://www.jsfiddle.net/8Yn7e/
When you set a variable that points to an existing array to point to a new array, all you are doing is breaking the link the variable has to that original array.
When you use array.length = 0 (and other methods like array.splice(0, array.length) for instance), you are actually emptying the original array.
Are you sure it really works?
I did a little experiment here, and trying to "add" an Array with a String resulted in a string.
function xyz(){
var a = [];
alert(typeof(a+$("#first").html()));
// shows "string"
}
http://www.jsfiddle.net/4nKCF/
(tested in Opera 11)

Getting undefined value from an array

Talk is cheap; I'd rather show the code:
//global var
var siblings = [];
var rand = new Date().getTime();
siblings.push('uin_' + rand);
alert(siblings['uin_' + rand]); // undefined
Why undefined? What I basically want to achieve is to have a global object that would be a storage where info about other objects get saved. But get back to my problem. I pushed the value then I want to alert it but get undefined... why undefined?
.push appends it to the array, siblings[0] contains it because it's the first element in (formerly) empty array.
If you want to determine the key yourself, do
siblings = {};
siblings['key'] = 'something';
Otherwise loop through the array if you want to access each element
for ( var l = siblings.length, i = 0; i<l; ++i ) {
alert( siblings[i] )
}
Note: arrays are objects so I could've set siblings['key'] = 'something'; on the array, but that's not preferred.
siblings is an array. You're pushing the value 'uin_'+rand onto it, so the keys would then be 0. Instead, you'd want to create an object.
var siblings={};
var rand=+new Date();
siblings['uin_'+rand]="something";
alert(siblings['uin_' + rand]);
Because you pushed a string value to array index 0, then tried to get a non-existant property on the array object.
Try using Array.pop().
In order to access an array, you need to use array indices, which basically refer to whether you want the 1st, 2nd, 3rd, etc.
In this case, use siblings[0].
Because siblings is an array, not an associative array. Two solutions:
//global var - use as an array
var siblings = [];
var rand = new Date().getTime();
siblings.push('uin_' + rand);
alert(siblings[0]); // undefined
//global var - use as an associative array
var siblings = {};
var rand = new Date().getTime();
siblings.push('uin_' + rand);
alert(siblings['uin_' + rand]); // undefined

Categories