Passing a variable inside a variable in javascript - javascript

I am trying to create a variable that will include another variable.
Example:
var options_id = ...
where 'id' is created dynamically through another variable so that the result could be
var options_1 = ...
var options_2 = ...
etc.
The 'id' is declared dynamically like this:
var id = itemid;
What would be the syntax to include the 'id' variable in the variable
var options_id
?

I suppose this is what your looking for:
window['options_' + id] = ...

Have you thought about using an object instead? You could do:
var id = itemid;
var options = {};
options['id'] = …;
Then access it using:
options.id

I think, that there is an Object in JS for that purpose.
For example:
var options = new Object();
var options.id = 'foo';
or if you want to use numeric indices then you can resort to Array

Related

How can i create object once we have values?

I am new to javascript so i dont know how to create object once we have values dynamically , so below code i have fullName and workerKey from dataItem now i want to create object selectedOwners with values of fullName and workerKey.
How can i achieve that task ?
ctrl.js
var selectedOwners = {};
$scope.addProcessOwner = function(dataItem){
var fullName = dataItem.fullName;
var workerKey = dataItem.workerKey;
console.log('WORKER KEY', workerKey);
}
You use an object initializer:
selectedOwners = {
fullName: dataItem.fullName,
workerKey: dataItem.workerKey
};
The object initializer is the {...} bit. Each of those two things inside it is a property initializer. The part before the : is the name, the part after is the value, which can be the result of any expression.
In your code, you'd already created the object (var selectedItem = {};). The code above will replace that object. If you just wanted to add to it, you'd just use assignment:
selectedItem.fullName = dataItem.fullName;
selectedItem.workerKey = dataItem.workerKey;
Which you use depends on whether it matters that you not create a new object.
Edited, as per comments:
var list = [];
$scope.addProcessOwner = function(dataItem){
var selectedOwners = {"fullname":dataItem.fullName,"workerKey":dataItem.workerKey};
list.push(selectedOwners);
}
// use list to populate output
You have already created the object so all you need to do is add the values into it.
var selectedOwners = {};
$scope.addProcessOwner = function(dataItem){
selectedOwners.fullName = dataItem.fullName;
selectedOwners.workerKey = dataItem.workerKey;
//This will print out the newly populated object
console.log(selectedOwners);
}

Create a multiple object with dynamic names

I created a function which allows to return an object whose name change to each loop.
I done this function like this :
function createObjPack(index){
var currentPack = packVehicule[key].libelle;
return [eval(currentPack + ' = {}' ), calcul(currentPack, key)];
};
The variable curentPack contains the name of the current object.
The return must generate a object which name match the value of currentPack
I thought read the currentPack directly into an eval() function for change dynamicly the name but, it doesn't work.
Someone can help me ?
Don't use dynamic variable names, use an object.
var packs = {}
function createObjPack(index) {
var currentPack = packvehicule[index].libelle;
var newPack = {};
packs[currentPack] = newPack;
return [newPack, calcul(currentPack, index)];
}

How to create Dictionary [Key : value] in jQuery

I have a input elements in html with two important attributes: id, and parentElementId.
I want to create a map/dictionary that looks like this: "id : parentElementId".
var parent = $(".people-autocomplete").map( function(){ return $(this).attr('id')+':'+$(this).attr('parent'); }).get() ;
for know I'm putting the values into a string, which I parse later on in the code. I presume there is a more elegant solution than this.
Use an object:
var obj = {};
$(".people-autocomplete").each(function() {
obj[$(this).attr('id')] = $(this).attr('parent');
});
You can then access the parent of a specific id:
var parent = obj.idName;
or through a string:
var idStr = 'idName';
var parent = obj[idStr];
And you can loop through:
for (idStr in obj) {
var parent = obj[idStr];
}
You can use JSON object for this purpose, You are confusing the usage of .map() in Jquery with map of other languages.
You can create a Json object like,
var xObj = {};
xObj.id = 'parentElemtnId';
alert(JSON.stringify(xObj)); // { id : 'parentElementId' }

Push to array a key name taken from variable

I have an array:
var pages = new Array();
I want to push my pages data to this array like this:
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
pages_order.push({datatype:info});
});
but this code doesn't replace datatype as variable, just puts datatype string as a key.
How do I make it place there actual string value as a key name?
I finally saw what you were trying to do:
var pages = new Array();
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
var temp = {};
temp[datatype] = info;
pages_order.push(temp);
});
$('li.page').each(function () {
//get type and info, then setup an object to push onto the array
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
obj = {};
//now set the index and the value for the object
obj[datatype] = info;
pages_order.push(obj);
});
Notice that you can put a comma between variable declarations rather than reusing the var keyword.
It looks like you just want to store two pieces of information for each page. You can do that by pushing an array instead of an object:
pages_order.push([datatype, info]);
You have to use datatype in a context where it will be evaluated.
Like so.
var pages = [];
$('li.page').each(function () {
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
record = {};
record[datatype] = info;
pages_order.push(record);
});
You only need one var it can be followed by multiple assignments that are separated by ,.
No need to use new Array just use the array literal []
You may add below single line to push value with key:
pages_order.yourkey = value;

Is it possible to replace sub object with other object in main object?

I want to replace the sub object with some other object in main object.
ex:
var mianobj = {"a":{"aa":{"aaa":"0000","bbb":"1111"}},"b":"222","c":"333"}
var newsubobj = {"n":"8888","g":"9999"}
console.log(mainobj.a.aa)
// this gives the sub object --> {"aaa":"0000","bbb":"1111"}
I want to replace this object with newsubobj.
I need the result as ::
console.log(mainobj);
// {"a":{"aa":{"n":"8888","g":"9999"}},"b":"222","c":"333"}
Thanks in advance.
Why you don't do it like that:
mainobj.a.aa = newsubobj
?
Ah, now we're getting somewhere. To update your question you have:
var mainobj = {"a":{"aa":{"aaa":"0000","bbb":"1111"}},"b":"222","c":"333"}
var subobjpath = "a.aa"; // this needs to be a string
var newsubobj = {"n":"8888","g":"9999"}
and you want to use subobjpath to replace a part of mainobj with newsubobj.
You can do so using code like this:
var path = subobjpath.split('.');
var obj = mainobj;
for(var idx=0; idx < path.length-1;idx++) obj = mainobj[path[idx]];
obj[path[path.length-1]] = newsubobj;
var mainobj = {"a":{"aa":{"aaa":"0000","bbb":"1111"}},"b":"222","c":"333"};
var newsubobj = {"n":"8888","g":"9999"};
mainobj.a.aa = newsubobj;
console.log(mainobj);

Categories

Resources