Create a multiple object with dynamic names - javascript

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)];
}

Related

How can I get the name of a property from inside an object to create a new property name?

I know there are a few other posts on this topic, but they don't seem to address my issue: link.
I want to be able to dynamically get the name of a specific property in an object so that I can use it to create a new property name inside another object. For example, I would get the property name startMin from foo (as in my code below) and then add text to the end of it (like startMin + Suffix) to create a new property name. How can I do this?
A related note: I've already figured out how to get the property value with foo[Object.keys(foo)[0]]. Though this works, I'm not sure why Object.keys gets the property value in this case since the examples I've found suggest Object.keys is supposed to get the property name not the property value. I'd love to know why?
I have included the pusdo code foo[Object.returnObjectName(foo)[0]] + 'Cal' where I want the name to be dynamically created. It doesn't work, of course.
var foo = {
startMin: 1000
};
var fooResults = {
// the property name here is psudo code
foo[Object.returnObjectName(foo)[0]] + 'Cal': foo[Object.keys(foo)[0]]
}
console.log('startMinCal: ' + fooResults.startMinCal) // This should log "1000" but won't until the object name inside `fooResults` is created correctly.
//
console.log(Object.keys(foo)); // I believe this gests the property name, but it exists inside an array, so won't work as a new property name
console.log(foo[Object.keys(foo)[0]]); // this gets the property value as expected.
UPDATED WORKING CODE:
var foo = {
startMin: 1000,
startMax: 3000
};
var fooResults = {
[Object.keys(foo)[0] + 'Cal']: foo[Object.keys(foo)[0]],
[Object.keys(foo)[1] + 'Cal']: foo[Object.keys(foo)[1]]
}
console.log('startMinCal: ' + fooResults.startMinCal)
console.log('startMaxCal: ' + fooResults.startMaxCal)
var foo = {
startMin: 1000
};
//Object.keys return all the keys in an object passed as parameter
//here your wanted key is at first position
var key = Object.keys(foo)[0];
//get the value
var value = foo[key]
//append whatever suffix you want
key += 'Cal';
var fooResults = {
//to use content of variable as key of object put variable in []
[key]: value
}
//another solution
//create emtyy object
var fooResults2 = {}
//use use variable name as index
fooResults2[key] = value
console.log('startMinCal: ' + fooResults.startMinCal) // This should log "1000" but won't until the object name inside `fooResults` is created correctly.
console.log('startMinCal: ' + fooResults2.startMinCal)

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);
}

Capturing variable names from a select

In the back end I have written some code that reads through a file and outputs to a list of JavaScript arrays for example, the page will see:
<script>
var peanuts = ["1","s","g","3","n"];
var cashewNuts = ["d","a","f","d","n"];
var PecanNuts = ["6","m","3","x","m"];
var BrazilNuts = ["j","n","7","v","s"];
var goingNuts = ["a","e","7","m","y"];
</script>
I then want to use an array based on the value of a somewhere else in that page.
So for example:
if($('select').val()===0){
alert(firstArray[1]);
}
My issue is that the variable names are decided on what is contained in the read file, I can't know this information. Is there a way to say for example
//collect the value from the select and assign it to a var
var varN = $('select').val();
//then collect another variable that has the variable name that
//equals the value of the 'varN'
I know this seems horrendous but unfortunately based on what I need to do, it is what I need to do :(
Yes. If for example your vars are in the global scope, you can do
var val = window[varN][0]; to get peanuts:1
If you do
var nuts = {
peanuts : ["1","s","g","3","n"],
cashewNuts : ["d","a","f","d","n"],
PecanNuts : ["6","m","3","x","m"],
BrazilNuts : ["j","n","7","v","s"],
goingNuts : ["a","e","7","m","y"]
}
then you can use
var val = nuts[varN][0];
If the variables are declared directly in <script>, you can use window[varN].

dynamic object properties javascript

Having issues with this code block:
var name = "";
var nutrients = {};
var tds = document.getElementById('data').getElementsByTagName('td');
name = tds[0].innerHTML;
nutrients[name].val = tds[1].innerHTML;
alert(nutrients.Energy.val);
If I take out the .val on both lines, the code works. I'm trying to dynamically create the "
nutrients" abject by extracting information from a table. "Energy", and all 50 of nutrient names must have a "value" and a "unit" property. Eventually this will be a loop.
Thanks for any help
When trying to assign
nutrients[name].val = tds[1].innerHTML;
the nutrients object is still empty, and nutrients["Energy"] (or whatever) will be undefined; throwing an exception when beeing assigned a property. Instead, use
nutrients[name] = {
val: tds[1].innerHTML
};

Passing a variable inside a variable in 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

Categories

Resources