Jquery Array Object - How To Add Suffix Variable To Index Names
I have this array object which initiates each index: var example = { 'hours': 0, 'overtime': 0, 'income': 0, 'expenditure': 0 }; However it is inside a .each() loop. Each index ne
Solution 1:
Here's an alternate way to do this that might work for you:
var employee = [];
var numEmpl = 100; // total number of employeesfor(var i = 0; i < numEmpl; i++)
employee[i] = {'hours' : 0, 'overtime' : 0, 'income' : 0, 'expenditure' : 0};
The above code gives you an array of objects, one for each employee. Each object (employee) property can be accessed individually like this:
employee[20].overtime = 10;
console.log(employee[20].overtime) // => 10
Alternately, you can update all info for a given employee at one time like this:
employee[30] = {'hours' : 45, 'overtime' : 5, 'income' : 1000, 'expenditure' : 0}
console.log(employee[30].overtime) // => 5
To add a new employee, simply do this:
employee.push({'hours' : 0, 'overtime' : 0, 'income' : 0, 'expenditure' : 0})
Solution 2:
Add new keys and delete old keys
var example = {
'hours': 0,
'overtime': 0,
'income': 0,
'expenditure': 0
};
var index = 0;
for (var key in example) {
example[key + index] = example[key];//adding new key with old valuedelete example[key];//delete old key
}
console.log(example);
Output:Object {hours0: 0, overtime0: 0, income0: 0, expenditure0: 0}
Solution 3:
Gerald's answer definitely is the best way to do it.
However note that it is also possible to evaluate string expressions as object fields inline. Here's how you do it:
let a = { ['foo' + 'bar' + 123]: 5 }
// a is now { foobar123: 5 }
Post a Comment for "Jquery Array Object - How To Add Suffix Variable To Index Names"