dynamically create variable from variable names - javascript

I have a dynamic number of files (structure, tab1, tab2, tab3, ...) that I load into my site.
For each of them I want to define variables like "total", "different", ....
dbVariables.structure.total = aaa
dbVariables.tab1.total = 123
dbVariables.tab2.total = 456
dbVariables. ... .total = xx
dbVariables.structure.different= aaa
dbVariables.tab1.different = abc;
dbVariables.tab2.different = def;
dbVariables. ... .different = xxx
Since putting them to [window] is not nice, i created dbVariables Object to store the variables there. I currently have a for loop that loads the files and I can even create dbVariable.tab1, dbVariable.tab2 etc. dynamically, but how would I stitch the last peace of information to it to?
var dbVariables= {};
for (i=0; i< fileNamesArray.length; i++){
filename = fileNamesArray[i];
processData(filename);
}
});
// the ".total" is not accepted :-(
function processData(filename){
dbVariables[filename].total = 123;
};

You can't do this:
dbVariables[filename].total = 123;
Because there is no dbVariables[filename], so you can set a property on undefined. You need to add it first.
function processData(filename){
dbVariables[filename] = {};
dbVariables[filename].total = 123;
};
But you might be better off if dbVariables was an array rather than an object unless you are certain that there are no duplicate filename.

You need to set dbVariables[filename] before adding the total. try something like that :
function processDatra(filename){
if(typeof dbVariables[filename] === 'undefined') dbVariables[filename] = {};
dbVariables[filename].total = 123;
};

Related

Setting nested object properties in JavaScript

How would I add a "property" to an object? I tried: players[data.id].name = data.name;
but it's not working.
Edit: this worked, thanks for the help guys!:
players[data.id] = {name: "Johnny"};
What I want to achieve: (data.id is already defined)
var players = {};
players[data.id].name = "Johnny";
players[data.id].age = 13;
console.log(players[data.id].name]); ---> Johnny
welcome to stackoverflow ! You need to define what players[data.id] is first.
Then you can assign data to it. In your example, you are only logging the name property of your object, remove the .name to show the whole object.
let data = { id: "test" };
var players = {};
players[data.id] = {}
players[data.id].name = "Johnny";
players[data.id].age = 13;
console.log(players[data.id]);
First, you have to declare 'players[data.id]' as an object.
The flow of the code would be like
var players = {};
players["dataId"] = {};
players["dataId"].name = "Johnny";
players["dataId"].age = 13;
console.log(players["dataId"].name);

Javascript create object with property as dynamic objects

I tried a lot searching and didnt get desired solutions.
What I want to achieve is
var myObject {
id1 : {
name:place_name,
location : place_loc
},
id2 : {
name:place_name,
location : place_loc
},
id3 : {
name:place_name,
location : place_loc
}
}
What I want to do is that Initially I want the properties "id1", "id2".. to be dynamic. And then dynamically assign name:place_name and other properties of each property.
I dont know the number of properties (id1,id2,id3...) hence would like to add them dynamically and following the addition of properties(id1,id2... ) I want to dynamically add the property values. (place_name & place_loc) of each id.
My code looks something like this.
var myObject = {};
myObject[idnumber1].place = "SomePlace1";
myObject[idnumber1].place = "SomeLoc1";
myObject[idnumber2].place = "SomePlace1";
myObject[idnumber2].place = "SomeLoc1";
But it gives error.
I know it seems simple doubt but any help would be grateful.
Thanks in advance. :)
You are trying to set a value of already assigned objects at keys "idnumber1", etc.
What you'll need is to initialize each objects for your ids like this:
var myObject = {};
myObject[idnumber1] = {};
myObject[idnumber1].place = "SomePlace1";
myObject[idnumber2] = {};
myObject[idnumber2].place = "SomeLoc1"
I would do it this way, it's not exactly what you did ask for, but I think it will become easier to change this later on.
function Place(name, location) {
this.name = name;
this.location = location;
}
var myObject = {}
myObject['id1'] = new Place('Foo', 'Bar');
myObject['id2'] = new Place('Internet', 'test');
console.log(myObject);
To dynamically create objects in your collection, you can use a numerical counter variable to create your object collection (myObject["id" + i] = {name: place_name, location: place_loc}).
An example:
var myObject = {};
for (i = 0; i < 20; i++){
myObject["id" + i] = {name: place_name, location: place_loc}
}
In practice, you can use a counter that you increment outside of a loop.

How to add a variable to a javascript/jQuery object?

Well, the problem is quite simple. I got an object of parsed table rows. Code for it is this:
var erg = [];
$("tr").each(function (index) {
var row = {};
var test = $(this).children();
row['column1'] = test[0].textContent;
row['column2'] = test[1].textContent;
row['column3'] = test[2].textContent;
row['column4'] = test[3].textContent;
row['column5'] = test[4].textContent;
row['column6'] = test[5].textContent;
row['column7'] = test[6].textContent;
erg.push(row);
});
And I wanna pass a variable var my_variable="blabla" to it without ruining the structure of the object. So how could i bring that object into a structure like this?:
Object{my_variable="my_variable_value"}, Object{my_table=[Object{...}, Object{...}]} //all the objects of the table
$.extend({}, erg, my_variable); only messed my object up.
I want it in that structure so i can pass it as json to my php script and filter my variable easily. Any tips, links, code snippets? :)
I'm not sure at which point you want to add that, but you may simply wrap your array with another object, and add your property to that same object.
This is basically what Florent's answer does, but using an object literal instead of a "class" and prototype:
// (your current code)
var wrapper = {
my_variable: 'something',
my_table: erg
};
You can define a class and add the needed variables to its prototype.
First you need a little utility to do that:
function createSharedStruct() {
// Define a shared structure
var Struct = function() {};
// Define a method to define a shared variable
Struct.share = function(variable, value) {
Struct.prototype[variable] = value;
};
return Struct;
}
And then, update your code:
// Create the shared structure
var rowClass = createSharedStruct();
// Register your shared variables
rowClass.share('my_variable', 'my_variable_value');
var erg = [];
$("tr").each(function (index) {
var test = $(this).children();
// Create a new row
var row = new rowClass();
row['column1'] = test[0].textContent;
row['column2'] = test[1].textContent;
row['column3'] = test[2].textContent;
row['column4'] = test[3].textContent;
row['column5'] = test[4].textContent;
row['column6'] = test[5].textContent;
row['column7'] = test[6].textContent;
erg.push(row);
});
// No matter when you share a variable, it will be defined among
// all instances of the same struct.
rowClass.share('my_other_var', 42);
Now you can access shared variables:
console.log(erg[0].my_other_variable); // 42
console.log(erg[1].my_other_variable); // 42
Demo available on JSFiddle.

Update nested attributes in a JavaScript object

I want to change 'hello' to 'hey' programmatically, the solution should work with any number of nested elements (I just use 2 levels to keep it simple).
var data = {level1: {level2 : 'hello' }};
I have access to the 'data' variable, the path ('level1/level2') and the new value ('hey').
I tried to do:
var parents = 'level1/level2'.split('/');
var target = data;
for(var i=0; i<parents.length; i++){
target = data[parents[i]];
}
target = 'hey';
The idea was to travel to the root
target = data
then 1 level deep
target = data['level1']
...keep going
target = data['level1']['level2'] //data['level1'] === target
and modify the contents
target = 'hey'
But it looks like a lose the reference to the original object (data) when I do (target = target['level2']).
I guess I can build a string with the path and then evaluate it:
eval("data['level1']['level2']='hey');
Is there a better solution that dosen't involve eval()?
There are two issues. First is that you keep using data inside the loop, which means you're trying to access the top level keys instead of the inner keys. Change target = data[parents[i]]; to
target = target[parents[i]];
The second is that when you change the variable target, you're not changing the data variable but target instead. If you drop out of the loop one iteration earlier you can update the object which is stored as a reference:
for(var i=0; i<parents.length-1; i++){
target = target[parents[i]];
}
target[parents[i]] = 'hey';
Demo: http://jsfiddle.net/Lherp/
Try something like this:
var data = {level1: {level2 : 'hello' }};
var parents = 'level1/level2'.split('/');
var target = data;
for(var i=0; i < parents.length - 1; i++){
target = target[parents[i]];
}
target[parents[i]] = 'hey';
Or am I missing something?
edit: I was missing something (sorry, should have tested it first..)

Object within object add property with JavaScript

I have an object within an object. It looks like this.
var myLib = {
object1: {}
}
My basic problem is that I wanted to end up like this. So I would like to do this dynamically I will not know the property's or additional objects until run time.
var myLib = {
object1: ({"A1":({"Color":"Blue",
"height":50})
})
}
From reading here on Stack Overflow I know that I can create an object within an object by simply going like this:
myLib.Object1["A1"] = "Something"
But this does not produce what I'm looking for.
I tried this syntax which I know is wrong but basically
mylib.Object1["A1"].["color"]="Blue";
so basically here is the question. I would like to create object "A1" under "mylib.Object" and immediately add property color = "blue" to "A1". I would need to do this for several other properties, but if I can figure out how to do this for one, I can figure it out for the rest. How can I accomplish this task?
No jQuery, please. Just plain old JavaScript is what I'm looking for.**
Once I create the object and properties I would imagine I can just use a for loop to loop through the properties for that object. Like so:
for(key in mylib.Object1["A1"]){}
Right?
You can create it all from scratch like this:
var myLib = {};
myLib.object1 = {};
// assuming you get this value from your code somewhere
var x = "A1";
myLib.object1[x] = {Color: "Blue", height: 50};
Or, if all values are in variables:
var myLib = {};
myLib.object1 = {};
// assuming you get this value from your code somewhere
var x = "A1";
var colorProp = "Color";
var colorPropValue = "Blue";
var heightProp = "height";
var heightPropValue = 50;
myLib.object1[x] = {}; // create empty object so we can then add properties to it
myLib.object1[x][colorProp] = colorPropValue; // add one property
myLib.object1[x][heightProp] = heightPropValue; // add another property
These syntaxes create identical results:
myLib.object1.A1 = {};
var x = "A1";
myLib.object1[x] = {};
The first can only be used when the property name is known when you write the code and when the property name follows the proper rules for a javascript identifier. The second can be used any time, but is typically used when the property name is in a variable or when it doesn't follow the rules for a javascript identifier (like it starts with a digit).

Categories