Skip to content Skip to sidebar Skip to footer

How Do I Dynamically Denote My Object Property Names?

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 -

Solution 1:

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);
}

Solution 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}));
}

Post a Comment for "How Do I Dynamically Denote My Object Property Names?"