Javascript newbie here. I currently have an associative array in the following format:
StringA: number,
StringB: number
Is it possible to map multiple strings to the same number? Something like this (some numbers may have a different number of Strings mapped to them):
StringA, StringB, StringC: number,
StringD, StringE: number,
StringF, StringG, StringH, StringI: number
Basically, I want holder to have the same value whether I write var holder = arr[StringA] or var holder = arr[StringC]. If it's not possible could someone point me in the right direction? Any help would be greatly appreciated!
You could use an object with a value for the object with multiple keys for one object.
Basically this creates a reference to the shared object. Then you could change the value inside of the object.
var temp = { value: 42 },
object = {
a: temp,
b: temp,
c: temp
};
console.log(object.a.value); // 42
object.b.value = 7;
console.log(object.c.value); // 7
Basically Js don't have associative array they are objects. Read this:
http://www.w3schools.com/js/js_arrays.asp
You need pointers to achive this, but JS not have pointers. But ther is a way to use pointers: use objects.
var assoc = [];
assoc["stringA"] = { value: 1};
assoc["stringB"] = assoc["stringA"];
assoc["stringC"] = assoc["stringA"];
assoc["stringD"] = { value: 10};
assoc["stringE"] = assoc["stringD"];
console.log("A: "+assoc["stringA"].value);
console.log("B: "+assoc["stringB"].value);
console.log("C: "+assoc["stringC"].value);
console.log("D: "+assoc["stringD"].value);
console.log("E: "+assoc["stringE"].value);
console.log("======== modify value ======");
console.log("\nModify A to 2")
assoc["stringA"].value = 2;
console.log("B: "+assoc["stringB"].value);
console.log("C: "+assoc["stringB"].value);
console.log("\nModify E to 20")
assoc["stringE"].value = 20;
console.log("D: "+assoc["stringD"].value);
console.log("E: "+assoc["stringE"].value);
Related
I declared six variables:
let L1, L2, L3, R1, R2, R3
and then I want to assign these six variables with the same value:
L1 = "something";
L2 = "something";
L3 = "something";
R1 = "something";
R2 = "something";
R3 = "something";
There must be a shorter way to do this right? I want to do it in a loop, because in this example we only have six variables, but in fact I have a lot of them.
The main way I see you being able to accomplish this is using an object (as others have already pointed out). You will still need to instantiate all the variables initially using the long-form syntax; but then you will be able to use a "for in" loop to actually assign all of the necessary values:
let something = {
L1: null,
L2: null,
L3: null,
};
for (let prop in something){
something[prop] = 1;
};
console.log(something);
Hope this helps!
I will directly answer your question, even though I think you shouldn't do that, you should think in a more "javascript" way of doing this.
That said:
const value = "something";
const numberOfVars = 100;
for( let i=0; i< numberOfVars; i++)
eval( "L"+ i + " = value" );
That would create the variables L0 to L99 with the value "something" inside. You could do that for any name, be it R, L or any string which is a valid javascript variable name.
Why not use an object instead?
const bubbles = {
bubbleL1,
bubbleL2,
bubbleL3,
bubbleR1,
bubbleR2,
bubbleR3
};
If you want to use array methods on it, you can extract an array of the values from the object with Object.values.
For your new question, you can fill an array with values, then destructure:
const [L1, L2, L3, R1, R2, R3] = new Array(6).fill('something');
console.log(L1);
console.log(R3);
If you want to give each variable its own name, but also have them grouped together so that you can use a blanket statement to set all their values, you got two easy options:
Option 1:
Use an array. An array will not allow you to name your variables, but they will be auto-assigned "names" according to their position (index) in the array. For example, if you made an array of the following values: "Cookie", "Money", and "Nothing." then they would be assigned numbers to reference them by, "Cookie" would be named "0", "Money" would be named "1", "Nothing." will be named "2" and so on... Here's an example of what an array looks like:
var nameOfArray = ["value1","value2","value3"];
and to access the value of an array, simply use that value's index:
nameOfArray[0]
(^^^ This would return "value1" ^^^)
So, if you think about it, that makes arrays very for-loop-friendly, so therefor this example looks very simple. Simply use the following to assign every variable in your array to the same value:
for(let i = 0;i < nameOfArray.length;i++){
nameOfArray[i] = "Whatever value I want.";
}
Option 2:
Use an object. An object is basically a group of named variables. The name of the variable is called the "key" and the value of the variable is called the "value". This is usually called a "key/value pair" For example:
var nameOfObject = {
variable1: "value1",
variable2: "value2",
};
Where "variable2" is a key, and "value2" is a value.
Then you can access each variable inside the object using simple dot or bracket notation.
Dot notation: nameOfObject.variableName
Bracket notation: nameOfObject["variableName"]
Setting all variables inside an object to the same value can be tricky. To do so, I usually use a for loop that iterates through all the keys in an object, and sets their values. In order to do so, you will first need to collect all the names of all the keys in the object. I simply use: Object.keys(nameOfObject) then I iterate through that array and assign each variable a value:
const objectKeyNames = Object.keys(nameOfObject);
for(let i = 0;i < objectKeyNames.length;i++){
nameOfObject[objectKeyNames[i]] = "Whatever I want to set it to.";
}
And it's that simple! All variables inside the object will be set to "Whatever I want to set it to."
it sounds like you are looking for a map rather than a list.
if you declare an object
var bubbles = {}
you can then access items by name
bubbles['bubbles1'] = 'something';
you can also loop through the items like a list later if you need to.
you can assign using left hand assignment like this:
let L1 = L2 = L3 = R1 = R2 = R3 = "something";
however that will cause a scope issue.
it would be better to declare then assign like
let L1, L2, L3, R1, R2, R3;
L1 = L2 = L3 = R1 = R2 = R3 = "something";`
Are you sure that you have like hundred variables that are not in fact parts of object?
Like let R1,R2,R3,L1,L2,L3 could be volume {left, right} for 3 audio track.
So you can write
let tracks = [{ right : 0, left : 0}, { right : 0, left : 0}, { right : 0, left : 0}]
L1 will become tracks[0].left and R3 will become tracks[2].right
With 100 tracks?
let tracksCount = 100;
let tracks = new Array(tracksCount).fill().map( t => ({ right:0, left: 0 }) );
Helping?
I want to create an array of JSON object without a key.How can this is achieved ..??
for example [{8,0,2}, {20,0,2}].
var hh = 9
var mm = 8
var qty = 2
var data = [];
data.push({hh,mm,qty})
it gives data like [{hh:9,mm:8,qty:2}]
I want array like [{9,8,2},{9,3,4}]
You example uses a new feature of ECMAScript 6 that is the shorthand syntax for initialising object properties. This line in your example:
data.push({hh,mm,qty});
is equivalent to this verbose one:
data.push({hh: hh, mm: mm, qty: qty});
An object in JavaScript will always have keys and values. There is no way to save just values in a plain object. However, there are two other solutions.
One is using an array:
data.push([hh, mm, qty]);
Note the square brackets substituting the curly ones. This will obviously push an array of three values onto the data array. When retrieving the values, you can just refer to their index, as an array's items will always retain their indices:
var data2 = [hh, mm, qty];
var hh2 = data2[0];
var mm2 = data2[1];
var qty2 = data2[2];
Another way of just "saving the values" is using a set, though the construction of a Set object will still require passing it an array:
data.push(new Set([hh, mm, qty]));
Accessing the data is less straightforward in this case, as the set will typically only let you iterate it. Unlike similar data structures in other languages, a JavaScript set will retain the order of inserted values. It can therefore be safely converted into an array:
var mySet = new Set([hh, mm, qty]);
var data3 = Array.from(mySet);
var hh3 = data3[0];
var mm3 = data3[1];
var qty3 = data3[2];
You can read more about sets here.
You can wrap it over another JSON object with a key I assume you want a JSON object.
Like this { [{8,0,2}, {20,0,2}] } but this with a problem - It is not a valid JSON.
I had a similar problem for one of my scenario. Then I realised
A top level JSON can't exist without a key!
Consider this example, you have another KV pair in JSON and also this array.
{
"somekey" : "somevalue",
[ {8,0,2}, {20,0,2} ]
}
You can fetch "somevalue" with the key "somekey". But how would you access the array? you can't :(
I would suggest you to use a top level key for the JSON and make this array as value of it's. Example:
{
"my array" : [ {8,0,2}, {20,0,2} ]
}
Without a key value pair, the object was not created. That's why its adding a key using the variable name
Look at this error. Its invalid code
var a = [{8,0,2}, {20,0,2}];
console.log(a)
You could push to an array instead of an object
var data = [];
var hh = 9
var mm = 8
var qty = 2
var data = [];
data.push([hh,mm,qty])
console.log(data)
You can't.
Object Literal Property Value Shorthands allow you to create an object where the property names are inferred from the variable names you use to pass the data into.
If you don't have variable names, then there is nothing for the JS engine to use to figure out what the property names should be.
Consider using a function instead.
console.log([time(8,0,2), time(20,0,2)]);
function time (hh, mm, qty) {
return {hh, mm, qty};
}
The result you get at the end makes sense. By doing {hh,mm,qty} you are effectively saying "Use the variable name as the key and its value as the value". It might help us more if you provide an example of how you intend to use the result and access the variables i.e. the shape of the object you want in the end.
That being said, there are a couple alternatives:
Using values as the keys
If you really wanted your object to look similar to {8,0,2} you could use those values as the keys (all keys get converted to strings anyways) so you could do the following:
var example1 = {8:undefined,0:undefined,2:undefined};
var example2 = {8:null,0:null,2:null};
var keys = [];
for(var name in example1) {
keys.push(name);
}
// keys = ["8","0","2"];
var otherKeys = Object.keys(example2);
// otherKeys = ["8","0","2"];
Setting the keys dynamically
var hh = 9;
var mm = 8;
var qty = 2;
var obj = {};
obj[hh] = null;
obj[mm] = null;
obj[qty] = null;
//obj = {9:null,8:null,2:null};
I'm not certain if this solves your problem or answers your question entirely but it might give you some more insight into what is happening and why. The above examples are a common way to create a quick lookup versus a dictionary with would have values in place of null or undefined.
I'm not sure if it's possible or not. So here I'm looking for an answer.
Is there any way to declare an object like:
var objectName = {
key1 : 'value1',
key2,key3 : 'value2;
}
I'm trying to combine key2 and key3 together.
If you don't want to assign the values like Patric Roberts says, create an array of keys and set the same value to those keys like so:
var obj = {};
obj['key1'] = 1;
// Array of keys
var arrayOfKeys = ['key2','key3','key4'];
// Common value for keys in array
var val = 2;
// Iterate the array
for(var k in arrayOfKeys) {
obj[arrayOfKeys[k]] = val;
}
console.log(obj);
You can also check this answer
You could use a slightly different approach, which will work on primitive values, too, by adding an object for keeping the same reference to different keys in the array. For example, you have a value object, like
temp = {
value: 42
}
and an array, like
object = {
key2: temp,
key3: temp
}
then you can use the keys independently for the value of the referenced object.
To change the value, you need to address it with
object.key2.value = 2000;
console.log(object.key3.value); // 2000
This question already has an answer here:
Javascript object when setting property all properties with same name are set
(1 answer)
Closed 1 year ago.
whenever i try to change the first object in the array's y, all the other objects y properties in my array also change, is there any way to prevent this, or a way to add multiple objects to an array that share the same properties ?
i have been trying everything to fix this(i was creating a game that uses a similar array for bullets firing and whenever i changed the y property of the first item in my array all the other y properties in the array changed with it) and i thought that this might be the problem ?
var obj = {x:30,y:20};
var arr = [];
for(var i = 0;i<3;i++) {
arr.push(obj);
}
arr[0].y = 40;
document.write(arr[0].y + " " + arr[1].y);
You can fix this by defining an object inside of .push().
This creates a new object for each element of the array, instead of the array containing multiple references to the same object.
var arr = [];
for(var i = 0;i<3;i++) {
arr.push({x:30, y:20});
}
arr[0].y = 40;
document.write(arr[0].y + " " + arr[1].y);
In JavaScript, objects are stored in memory as pointers to the values inside the object. This is different to how primitive data types (int, char, etc.)
A good way to show this is to try printing out the object, vs printing out an int:
HTML:
<div id="anelementhere"></div>
<div id="anotherelementhere"></div>
JS:
var x = 5;
var obj = {x:30,y:20};
document.getElementById("anelementhere").innerHTML = x;
document.getElementById("anotherelementhere").innerHTML = obj;
JSFiddle: https://jsfiddle.net/d3ohpqqp/
You should be able to see something akin to:
5
[object Object]
Now, knowing this, what's stored in the array is NOT {{x:30, y:20}, {x:30, y:20}, {x:30, y:20}}, but {[object Object], [object Object], [object Object]}, which all point to ONE {x:30, y:20}
This is what makes all the y properties change after changing one. Now a simple solution, as #IrkenVader has shown is where you initialize the object when you put it into the array.
However, if for some reason you still want the original object outside of the array, this is another solution:
var obj = {x:30,y:20};
var arr = [];
for(var i = 0;i<3;i++) {
arr.push({x:obj.x, y:obj.y});
}
arr[0].y = 40;
document.write(arr[0].y + " " + arr[1].y);
JSFiddle: https://jsfiddle.net/9gzyr38x/
you are making a single obj and passing a reference to the same object, 4 times in your array
instead you could try creating new objects in each iteration:
var arr = [];
for(var i = 0;i<3;i++) {
arr.push({x:30,y:20});
}
arr[0].y = 40;
document.write(arr[0].y + " " + arr[1].y);
You could also look up the various ways to "clone" an object. angular, jquery and underscore all provide methods to do so, or you can check out How to clone js object?
As well as the answer #IrkenInvader gave, you can also use jQuery to very easily perform a deep-copy of an object:
var obj = {x: 30, y: 20};
var arr = [];
for(var i = 0; i < 3; i++) {
arr.push(jQuery.extend(true, {}, obj));
}
arr[0].y = 40;
document.write(arr[0].y + " " + arr[1].y);
I am in bit of a puzzle, recently I had worked on a project where use of javascript was necessary. Everything is working fine I just need to know how does it work
eg : I had a dynamic variable count, which use to get some value, lets say I get the value as var count = 6;
Now when I put this in array {count : count }
I get the output as {count : 6}
Now my doubt is the output should have been { 6 : 6} as count should have been replaced with its value but it didn't happen so. Why is happening ? and how is this working properly ?
The key value pairs treat the key as a literal and the value as a variable.
so:
var count = 6;
var o = {count: count}; // results in {count: 6}
but to use a variable as the key, you can do this:
var count = 6;
var o = {};
o[count] = count; // results in: {6: 6}
The JavaScript object initialisation syntax lets you use bare words. If you do this:
{ foo: 6, bar: 12 }
It's equivalent to this:
{ 'foo': 6, 'bar': 12 }
What you want is to assign directly, like so:
var foobar = {};
foobar[foo] = 6;
foobar[bar] = 12;
In JavaScript associative arrays (or most associative arrays for that matter), the left side is the key, and the right side is the value. -> {key:value}
When you put {count:count} when you have a count variable beforehand (let's say its value is 10), what will happen is it will be read as {count:10}.
The left-hand side, or the key, is not a variable, but a constant.