I have an object defined below.
var obj = { 'group': ['a', 'b'],
'value': 10
}
Please note that group array can have n values. This is just an example. I want to create dynamic variables with names in array and assign their sum equal to value i.e 10. So for this particular object I want the following result.
First create Variables
var a, b
Then assign a + b = 10
Similarly for n values in array, I want
var a,b, ...n
a+b+....+n = 10
3 Answers 3
I think you need a function in your object, if i understand you right
var obj = {
group: [1, 2, 3],
value: function(){
return this.group.reduce((a, b) => a + b, 0);
}
}
obj.value();//6
you can edit obj.group array and get new value of this array by calling function obj.value()
but if you mean(again not sure, cause it is hard to understand) to make this value from variables called "a", "b" and etc you can try this code
var a = 1;
var b = 2;
var obj = {
group: ["a", "b"],
value: function(){
return this.group.reduce((v_prev, v_current) => v_prev + eval(v_current), 0);
}
}
obj.value();//3
Not the best idea to use eval, but it works. This code will find the sum of variables "a" and "b"
Comments
look at this code i think this would help you:
var obj = {
'group': [5, 5],
'value':function(str){
return this[str].reduce(add)
}
};
function add(a,b){
return a+b
}
console.log(obj.value('group'))
Comments
You can use an object instead:
var obj = {
'group': ['a', 'b'],
'value': 10
}
var groupNames = obj.group,
groupCount = groupNames.length,
val = obj.value / groupCount, //divide the obj.value to total group count
resultObj = {};
for (var i in groupNames) {
resultObj[groupNames[i]] = val; //add properties to resultObj based on group name and assign its value
}
//you can use the object properties to access your "dynamically created variables"
for (var i in resultObj) {
console.log('Your variable name is "' + i + '" and the value is ' + resultObj[i])
}
NOTE: It is not sure the logic on a + b + ... n = obj.val so, I have used average.
That is - obj.val / obj.groups.length.
a=10andb=0what you want? It satisfiesa+b=10.