1
for (var i = 0; i < 7; i++) {
    var _name = moment().subtract('days', i).format('dddd');
    week_count.push({
        _name: 0
    });
}

This is what I am attempting to do - however, this creates a list of objects that have properties named _name, how can I go about doing this? I tried executing it like so { moment().subtract('days',i).format('dddd') : 0 }, but this gave in to a Syntax Error. How do I go about achieving this?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Louis93
  • 3,843
  • 8
  • 48
  • 94

2 Answers2

4

You can't specify dynamic property names inside an object literal, but you can use bracket syntax instead:

for (var i = 0; i < 7; i++){
    var _name = moment().subtract('days',i).format('dddd');
    var obj = {};
    obj[_name] = 0;
    week_count.push(obj);
}
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
2

You need to use subscript notation to specify the key dynamically

for (var i = 0; i < 7; i++) {
    var _name = moment().subtract('days', i).format('dddd'), object = {};
    object [_name] = 0;
    week_count.push(object);
}

You might be able to shorten it a little bit, like this

for (var i = 0; i < 7; i++) {
    var object = {};
    object[moment().subtract('days', i).format('dddd')] = 0;
    week_count.push(object);
}

If you are looking for a way to do this in one line, then you might want use Object.defineProperty , like this

for (var i = 0; i < 7; i++) {
    var _name = moment().subtract('days', i).format('dddd');
    week_count.push(Object.defineProperty({}, _name, {value:0,enumerable:true}));
}
thefourtheye
  • 233,700
  • 52
  • 457
  • 497