1

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 needs a unique identifier like: hours0 hours1.

The old format that I used to append a suffix is bulky.

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

I've tried the following.

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

But it results in: Uncaught SyntaxError: Unexpected token +

any ideas?

Community
  • 1
  • 1
Swift
  • 61
  • 1
  • 4
  • 8
  • 1
    using brackets is the correct way actually – Alex Sep 04 '14 at 10:33
  • I don't think there is another way to do this, perhaps you can just define `e = example` and then `e['hours' + index] = 0; etc...` and finally `example = e` – Rob Schmuecker Sep 04 '14 at 10:39
  • You have to use bracket notation - for a full explanation, see http://stackoverflow.com/questions/9708192/use-a-concatenated-dynamic-string-as-javascript-object-key – Joe Sep 04 '14 at 10:39
  • Thanks guys, I hear you – Swift Sep 04 '14 at 10:53

3 Answers3

2

Here's an alternate 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 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})
Gerald LeRoy
  • 1,227
  • 2
  • 11
  • 17
1

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


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

vikrant singh
  • 2,091
  • 1
  • 12
  • 16
0

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 }
iGoodie
  • 153
  • 1
  • 9