This question already has answers here:
Use dynamic variable names in JavaScript
(19 answers)
Closed 9 years ago.
Let's think about this:
var list = [a1:"123",b2:"234",c3:"345"];
This list obj can create variables by key name like this?
var a1 = list[0];
var b2 = list[1];
var c3 = list[2];
When you use [] notation, you can only create arrays with numeric indexes. To have named properties, you must use {} object notation:
var list = { a1: "123", b2: "234", c3: "345" };
You can then access them as list.a1, list.b2, and list.c3.
The question is not clear. What you show in the example is valid. But you could also create variable names like you suggest like
for( var key in list ) {
window[key] = list[key];
}
This way you will end up having a1, b2 and c3 variables with the desired value, however, these will be globals.
First of all you have a mistake, you are trying to merge hash array and regular array. You should either announce an array like this:
var list = ['123', '234', '345']
and then
var a1 = list[0]
and so on, or announce it like hash array and it will look like this
var list = {'a':'123','b':'234','c':'345'}
var a1 = list.a
Related
This question already has answers here:
Merge keys array and values array into an object in JavaScript
(14 answers)
Closed 1 year ago.
I'm using local storage to get an arrays of strings,
First value attrIds is as follows,
var attrIds = localStorage.getItem('attributeids');
attrIds = JSON.parse(attrIds);
Second value confOptions is as follows,
I want something like this,
144: "5595"
93: "5487"
I have tried creating a loop inside the loop and tried to set the key and value but it's not working. I have also tried to set the single JSON object as key and setting value as '' but couldn't move further with that.
Does anyone have any idea regarding this?
You can accomplish this using a simple for loop, accessing the items from the arrays, and assigning properties to an empty object.
const keys = ['144', '93'];
const values = ['5595', '5487'];
const obj = {};
for (let i = 0; i < keys.length; i++) {
obj[keys[i]] = values[i];
}
console.log(obj); // prints { 144: '5595', 93: '5487' }
Create a nested array and then use Object.fromEntries().
const
a = ["144", "93"],
b = ["5595", "5487"],
c = Object.fromEntries(a.map((v, i) => [v, b[i]]));
console.log(c);
Using a for loop, you could do something like:
var attrIds = localStorage.getItem('attributeids');
attrIds = JSON.parse(attrIds);
confOptions = ["5595", "5487"]
const object = {};
for(let i=0; i<attrIds.length;i++)
object[attrIds[i]] = confOptions[i]
This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 4 years ago.
This is a very stripped down example of what I'm trying to do. These arrays are generated with server side code and I can't know which arrays will be there
except that they will always be 'array' followed by a number.
var array1 = ['cat','dog','fish','bird'];
var array2 = ['taco','pizza','burger','salad'];
var array3 = ['maple','elm','pine'];
The user selects an option from select-1
<select id="select-1" onchange="getArray()">
<option value="1">Pets</option>
<option value="2">Foods</option>
<option value="3">Trees</option>
</select>
Then I need my function to access the correct array corresponding to the value of select-1. Every option that appears in select-1 will have a corresponding array.
function getArray() {
var x = document.getElementById("select-1").value;
//how do I access "arrayx"?
var y = arrayx[0];
}
How can I write the function to get a value from the correct array? I need something like
arrayname = 'array' + x;
but I can't figure out how to get there from here.
Here is a fiddle that's set up to experiment with: http://jsfiddle.net/6yor1kp5/9/
If it is in the global context in a browser, you can use window[arrayname].
e.g.
var y = window["array"+x][0];
in your fiddle.
You could just follow #Pointy and surround the arrays in another array. In your current situation you'd have to append the arrays into arrayx when you load the arrays from the server.
var arrayx = [
['cat','dog','fish','bird'],
['taco','pizza','burger','salad'],
['maple','elm','pine']
];
You can use eval function for this -
var array1 = ['cat','dog','fish','bird'];
var array2 = ['taco','pizza','burger','salad'];
var array3 = ['maple','elm','pine'];
//if you want to use array1
var array = eval("array" + 1);
console.log(array);
But one should never ever use eval
This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?
(69 answers)
Closed 5 years ago.
I need to merge two javascript object and set it to my global object. I'm using "Object.assign" method but it doesn't work.It works right when it called first time. But I need to merge each time my new object to the global object. But it doesnt work more first time ,it makes my global just same as last object.Do you know any other way to make it ? Thanks in advance :/
Javscript codes :
//global object
Admin.bufferCreateJSON={};
Admin.createBufferJSON=function(){
var B_name=$("#B_name").val();
var B_description=$("#B_description").val();
var B_bufferType=$("#bufferTypeSelect").val();
var bufferData={};
var common = {'name': B_name,'description': B_description};
bufferData=Object.assign(bufferData, common);
var bufferType={ 'bufferType[id]': B_bufferType}
//following codes works right
bufferData=Object.assign(bufferData, bufferType);
//Admin.bufferCreateJSON is my global variable
// But when I want to merge it to my global variable it doesnt work
Admin.bufferCreateJSON=Object.assign(Admin.bufferCreateJSON, bufferData);
//shows me just last one
console.log(Admin.bufferCreateJSON);
}
let mergedObj = Object.assign({}, obj1, obj2, obj3); is the best way.
Snippet of your case:
var Admin = {
bufferCreateJSON: {
a: 123,
b: 321,
}
}
Admin.createBufferJSON=function(tmp){
var B_name = 'B_name' + tmp; //$("#B_name").val();
var B_description = 'B_description' + tmp; //$("#B_description").val();
var B_bufferType = 'B_bufferType' + tmp; //$("#bufferTypeSelect").val();
var common = {'name': B_name,'description': B_description};
var bufferData=Object.assign({}, common);
var bufferType={ 'bufferType[id]': B_bufferType}
bufferData=Object.assign({}, bufferData, bufferType);
Admin.bufferCreateJSON=Object.assign({}, Admin.bufferCreateJSON, bufferData);
console.log(Admin.bufferCreateJSON);
}
Admin.createBufferJSON(1)
Admin.createBufferJSON(2)
Console output:
Object {a: 123, b: 321, name: "B_name1", description: "B_description1", bufferType[id]: "B_bufferType1"}
Object {a: 123, b: 321, name: "B_name2", description: "B_description2", bufferType[id]: "B_bufferType2"}
Object contain a and b from globals object and name, description, bufferType[id] are replaced as expected.
if you want only to add new properties without replacement of exists properties you can change assign order:
Admin.bufferCreateJSON=Object.assign({}, bufferData, Admin.bufferCreateJSON);
not sure how to ask tbh :)
I'm used of PHP's associative arrays so much that I struggle to understand how to create an "named array" of objects.
Example:
I have two arrays, two ints and one boolean. This represents one of my entities. I have multiple entities on which I'm doing some work.
In PHP I would write:
$entitites[$entitity_id]['items'][] = $item;
$entitites[$entitity_id]['items_status'][] = $item_status;
$entitites[$entitity_id]['items_count']++;
and so on..
How do I do this with objects in JS?
var entities = {items:[], items_status: [], items_count: 0};
entities[entity_id].items.push(item)
How does one name his object for later access (via name or in my case, entity_id?)
This code doesnt work for me to this extend that my webpage goes blank without any errors produced :S
I also tried this:
var entities = {};
var entity = {items:[], items_status: [], items_count: 0};
but then I dont know how to always add values to already existing object in entities object and how to call that exact object via name eg. entity_id.
Halp :(
Keep entities as an object. Then you can just go ahead and add each entity_id as a key and an object which has all the details of that entity as the value.
var entities = {};
entities["1234"] = {
"items" : [],
"items_status" : [],
"items_count" : 0
};
There are 2 types involved here: Objects & Arrays.
Arrays are simple and you're probably familiar with them from any other language:
var myArray = []; // this is an empty array
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
// you could also use "var myArray = [1, 2, 3];" instead
alert(myArray[1]); // alerts the value 2
Note: arrays are actually objects, and can have non-index properties as well
You can also use various array functions such as .push(), .pop(), .shift() and so on to mutate the array instead.
Objects share the square brackets notation, but the purpose is different:
var myObject = {}; // this is an empty object
myObject[0] = 1;
myObject[1] = 2;
myObject[2] = 3;
alert(myObject[1]); // alerts the value 2
// but also...
myObject['prop'] = 4;
alert(myObject['prop']); // alerts the value 4
// and
myObject.prop2 = 5;
alert(myObject.prop2); // alerts the value 5
// and lastly
alert(myObject.prop); // alerts the value 4
So while arrays are accessed by index, objects are accessed by property names.
As for your entities, it looks like an array of objects. Lets see how we can do that:
function Entity() {
this.items = [];
this.items_status = [];
this.items_count = 0;
}
var entitites = [];
entities.push(new Entity());
entities[0].items = [1, 2, 3];
entities[0].items_status = ['good', 'good', 'poor'];
entities[0].items_count = 3;
Or you can wrap insertion in a more elegant function:
Entity.prototype.insert(item, status) {
this.items.push(item);
this.items_status.push(status);
this.items_count++;
}
entities[0].insert(4, 'excellent!');
If you want to keep control of the indexes in your JS array you can do so by not using .push() :
var entities = [];
entities[5] = {items:[], items_status:[], items_count:0};
Just replace 5 by your integer entity_id variable, and there you go.
You can use a regular javascript object to create the associative array you're looking for.
Actually it's PHP's implementation that's abit off but all they do is call it different (associative array) to most other language that simply refer to it as an object or hash.
You can use numeric keys in JS and still access them with the [] square brackets.
It works like this:
var my_obj = {};
my_obj[5] = 'any value';
console.log(my_obj); // {5: 'any value'}
JS will not add any redundant undefined to missing indexes either so when looping over the collection you won't loop over undefined.
Also, I can access the object by using the key as a string or as number so you won't have to check if the key is the right type. Taken from the above example:
console.log(my_obj['5']); // 'any value'
console.log(my_obj[5]); // 'any value'
JS Objects are the equivelant of PHP assoc arrays except JS objects are much more flexible than PHP's associative arrays.
The only downside to this is that you can't have duplicate keys.
No two keys may exist that share the same name, in an array if you .push(an_item) it will create a new index making even a duplicate data entry unique but when overwriting a key with a new value only the last value will persist, mind that :)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Dynamically creating keys in javascript associative array
usually we initialize an array like this:
var ar = ['Hello', 'World'];
And for access to it's values we do:
alert(ar[0]); // Hello
But I want a custom index to assign, ex:
var ar = ['first' => 'Hello', 'second' => 'World'];
and then
alert(ar['first']);
But I can't find how, is there something like this that I could do for assign?
Thank's!
You could use Object instead of Array, you can specify named properties for object
var ar = {
first: 'hello',
second: 'world'
};
alert(ar['first']);
Also you can just assign properties with string keys to your array, this will also work:
var ar = [];
ar['first'] = 'first';
alert(ar['first']);
You need to use an Object.
var obj = {'first': 'hello', 'second': 'world'};
alert(obj.first);
Objects in JavaScript are just property bags (hashtables).
You can:
var ar = {};
ar["name"] = "Dave";
ar["salary"] = "Millions";
alert(ar.name); //Dave
alert(ar["salary"]); //millions
JavaScript allows you to be pretty flexible in how you create these objects.
JavaScript doesn't have associative arrays as such, but object literals:
var obj = {foo:'bar'};
obj.something = 'else';
//or:
obj['foo'] = 'BAR';
JS won't make a fuss if you create named indexes on an array (because the Array object traces back to the Object prototype) but you'll loose all use of Array features (methods like sort, or the magic length property, to name just a few)
just use
var h = new Object(); // or just {}
h['one'] = 1;
h['two'] = 2;
h['three'] = 3;
// show the values stored
for (var k in h) {
// use hasOwnProperty to filter out keys from the Object.prototype
if (h.hasOwnProperty(k)) {
alert('key is: ' + k + ', value is: ' + h[k]);
}
}
You can do this:
var ar = {
'first' :'Hello',
'second' : 'World'
};
As you can see, this is the way you initialize objects in Javascript. Javascript blurs the lines between associative arrays and objects.
You can then access this with:
ar['first']
Or even:
ar.first
Also, you could leave out the quotes in the key initialization, like so:
var ar = {
first :'Hello',
second : 'World'
};