I have a complex javascript object with an array. When I try to set the value for one attribute of an index, it's applied to all items of the array.
Here is a basic example:
var obj = new Object();
obj.arr = [];
obj.arr[0] = {pos:[0,0]};
obj.arr[1] = {pos:[0,0]};
Now if i set a value for an attribute of the object, via a specific index,
obj.arr[0].pos = [10,10];
obj.arr[1].pos = [5,5];
Here it seems to be setting the value [5,5] for both items of the array. The resulting values are:
console.log(obj.arr[0].pos) returns [5,5]
and
console.log(obj.arr[1].pos) also returns [5,5]
My actual object is far more complex, but this is the basic idea of what's happening...
Any ideas?
They share the same link, i.e. several variables/properties of an object are referring to the same value.
Exact answer (where's the error) depends on how your object is composed.
var nested = {a:1};
var obj = {arr:[]};
obj.arr[0] = {pos:0, n:nested};
obj.arr[1] = {pos:0, n:nested};
obj.arr[0].pos = 1;
obj.arr[1].pos == 1; // false
obj.arr[0].nested.a = 2;
obj.arr[1].nested.a == 2; // true
Assignment of the same array/object literals is not the same.
var a = [0];
var b = [0];
b[0] = 1;
a[0] == 1; // false
b = a;
a[0] = 2;
b[0] == 2; // true
a = b = [0];
a[0] = 1;
b[0] == 1; // true
Related
var array = [[2,3,4],[4,5,6],[2,3,9]];
var number = 9;
If I have this nested array and this variable how do I return the index
where the sub-array with the number is. So the final result should be 2 or.
So far I have:
var indexOfRemainingArray = array.filter(function(item,i) {
if(item != number) {
return i;
}
});
I would like to know how to use map or filter functions for this.
Use Array#findIndex to find the index, and use Array#indexOf in the callback to check if the sub array contains the number at least once.
var array = [[2,3,4],[4,5,6],[2,3,9]];
var number = 9;
var indexOfRemainingArray = array.findIndex(function(sub) {
return sub.indexOf(number) !== -1;
});
console.log(indexOfRemainingArray);
And if you need both indexes, you can assign the result of the inner indexOf to a variable:
var array = [[2,3,4],[4,5,9],[2,3,1]];
var number = 9;
var innerIndex;
var indexOfRemainingArray = array.findIndex(function(sub) {
innerIndex = sub.indexOf(number);
return innerIndex !== -1;
});
console.log(indexOfRemainingArray, innerIndex);
I find numerous guides on how to add variables to existing objects, but nowhere how to add an "existing" variable to an existing object.
I have a whole list with variables already defined in my script. e.g.: a, b, c, d.
and they all have their own values.
Now I want to call a function on all these variables and then show the variable-names and outcome in console.
Therefor I want to create an object out of them to loop through. How do I do this?
This is my workflow:
Values are created in various places in the script:
a = 1.333;
b = 1.64252345;
c = 2.980988;
I create the object and try to add the already existing variables (this is where I fail):
var abc = {};
abc.a;
abc.b;
abc.c;
I want to loop through the object, flooring all numbers, and printing the variable-name with the returned number:
var i;
for (i = 0; i < abc.length; ++i) {
var variablename = Object.keys(abc[i]);
var flooredvalue = floor(abc[i]);
var abc[i] = flooredvalue; // Save the floored value back to the variable.
console.log(variablename+": "+flooredvalue);
}
My desired output in console.log:
a = 1
b = 1
c = 2
Looping through the array of object keys will be a good idea.
a = 1.333;
b = 1.64252345;
c = 2.980988;
var abc = {};
abc.a = a;
abc.b = b;
abc.c = c;
var i;
var keys = Object.keys(abc);
console.log(abc['a'])
for (i = 0; i < keys.length; i++) {
var key = keys[i];
var flooredvalue = Math.floor( abc[key] );
abc[key] = flooredvalue;
window[key] = flooredvalue; //global variable change.
}
console.log(a);
console.log(b);
console.log(c);
I have an object with one key value as given below -
var a = {};
a.x = "randomvalue";
My requirement is to get access the value "randomvalue", but the catch is I dont know that the property name is "x".
Simplest way to get the value??
Try:
var v, i;
var a = {};
a.x = "randomvalue";
for (x in a) {
if a[x] === "randomvalue" {
v = x;
i = "randomvalue";
}
}
Then v contains the object key and i contains the object value (although you don't really need it).
Or, if you know the value index:
var obj = { first: 'someVal' };
obj[Object.keys(obj)[0]]; //returns 'someVal'
I have a js object which looks like this:
var detailsArray = [
{a0 :1,
b0 :'A'},
{a1 :2,
b1 :'B'},
{a2 :3,
b2 :'C'},
{a3 :4,
b3 :'D'}];
This is how the object is created from the server side. On the client side I want to retrieve the value of all 'a's and add them to an array. The problem is that the variable name is changing depending on the index number. I have tried using underscore.js to do something like this:
var variableA = new Array();
for(var i = 0;i<detailsArray.length;i++){
var temp = 'a' + i;
variableA[i] = _.pluck(detailsArray,temp);
}
But this does not work. Can anyone tell how to get the values??
There is two ways for accessing properties of object in javascript : using the dot like you just done, or using the array syntax style.
var obj = {'a':5};
obj.a
obj['a']
So with your code, this would give this :
var variableA = new Array();
for(var i = 0;i<detailsArray.length;i++){
variableA[i] = detailsArray[i]['a' + i];
}
With underscore, you could do:
_.reduce(_.map(detailsArray, function(o, i) {
return o['a' + i];
}), function(a, b) {
return a + b;
});
And with native JS in newer browsers:
detailsArray.map(function(o, i) {
return o['a' + i];
}).reduce(function(a, b) {
return a + b;
});
You can also do it like that:
for (var i = 0; i < detailsArray.length; i++)
alert(eval("detailsArray[" + i + "].a" + i));
The code I provide will alert all the values corresponding to as in the json array, but obviously you can do whatever you want with the values obtained.
Here I am counting that all the keys will be of the kind a smth, but I suppose this is a safe assumption.
here's one possible implementation
var tmp = [];
for (var i = 0; i < detailsArray.length; i++) {
var obj = detailsArray[i]; // current object at index
for (var props in obj) { // iterate properties in current object
if (props.charAt() == "a") { // if starts with a....
tmp.push(obj[props]); // add value to array
break; // stop the property iteration and move to next object
}
}
}
console.log(tmp); // [1,2,3,4]
var a = new array();
a[1] = 'A';
b[10] = 'B';
console.log(a);
/[undefined, "A", undefined, undefined, undefined, undefined, undefined, undefined,
undefined, undefined, "B"]/
I want to remove undefined element
but what is the process??
First of all, jQuery has nothing to do with this.
Second, arrays are "autofilled". If you define index 10, all indexes 0 - 9 will be occupied automatically, that's just the way Javascript arrays work.
What you're looking for is probably an object:
var a = {};
a[1] = 'A';
a[10] = 'B';
or
var a = {
1 : 'A',
10 : 'B'
};
In this case you can use an Object instead of an Array like so:
var a = {}; // or var a = new Object();
a[1] = 'A';
a[10] = 'B';
a['foo'] = 'bar';
a.bar = 'foo'; // same as a['bar'] = 'foo';
console.log(a);
Arrays always start at 0 and then go up to the last filled index.
You could use an object to solve your problem:
var a = {};
a[1] = 'A';
a[10] = 'B';
well, to remove those undefined parts do
a[0] = 'A';
a[1] = 'B';
In your snippet, you fill the element with index 10 which forces the ECMAscript to create an array with 10 fields. There are no definitions for all that fields between 1 and 10, which means those are correctly undefined.
To remove that fields you either have to set a proper value or map the non-undefined values into a new array which would just be unnecesarry if you create a correct array in the first place.
Create an true object instead of an array (which actually also is an object) to have your desired behavior.
var a = {};
a[1] = 'A';
a[2] = 'B';
console.log(a);