Jquery Array Object - How to add suffix variable to index names

I have this array object that triggers each index:

var example = { 'hours': 0, 'overtime': 0, 'income': 0, 'expenditure': 0 };

However, it is inside the loop .each(). Each index need a unique identifier type: hours0 hours1.

The old format I used to add the suffix is ​​cumbersome.

example['hours'       + index] = 0;
example['overtime'    + index] = 0;
example['income'      + index] = 0;
example['expenditure' + index] = 0;

I have tried the following.

var example = { 'hours'+index: 0, 'overtime'+index: 0, 'income'+index: 0, 'expenditure'+index: 0 };

But this leads to: Uncaught SyntaxError: Unexpected token +

any ideas?

+1
source share
3 answers

Here's an alternative way to do this that might work for you:

var employee = [];

var numEmpl = 100; // total number of employees

for(var i = 0; i < numEmpl; i++)
  employee[i] = {'hours' : 0, 'overtime' : 0, 'income' : 0, 'expenditure' : 0};

 

The code above gives you an array of objects, one for each employee. Each object (employee) can be accessed individually:

employee[20].overtime = 10;

console.log(employee[20].overtime) // => 10

 

:

employee[30] = {'hours' : 45, 'overtime' : 5, 'income' : 1000, 'expenditure' : 0}

console.log(employee[30].overtime) // => 5

 

, :

employee.push({'hours' : 0, 'overtime' : 0, 'income' : 0, 'expenditure' : 0})
+2

 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 value
       delete example[key];//delete old key
   }
   console.log(example);


: Object {hours0: 0, overtime0: 0, income0: 0, expenditure0: 0}

+1

Gerald's answer is definitely the best way to do this.

However, note that you can also evaluate string expressions as inline fields of an object. Here's how you do it:

let a = { ['foo' + 'bar' + 123]: 5 }
// a is now { foobar123: 5 }
0
source

All Articles