1

I have the following array

  const lastThreeYearsArr = [currYear, currYear-1, currYear-2 ]

I need to define an object as:

var obj = {lastThreeYearsArr[0]: 0, lastThreeYearsArr[1]: 0, lastThreeYearsArr[2]: 0};

But using the array as key doesn't seem to work in javascript. Is there a way to access the array value and put it as key in the object.

Kim
  • 2,070
  • 5
  • 33
  • 46
  • 2
    [Computed property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names) – ASDFGerte Apr 26 '18 at 15:36

4 Answers4

2

You could create a new object by iterating the keys and use Object.assign with computed property names.

var lastThreeYearsArr = ['currYear', 'currYear-1', 'currYear-2'],
    object = lastThreeYearsArr.reduce((o, k) => Object.assign(o, { [k]: 0 }), {});
    
console.log(object);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can specify the properties using bracket notation instead of the object literal notation. For example:

const x = [2011, 2012, 2013]
let y = {}
y[x[0]] = 0
DaveG
  • 445
  • 1
  • 3
  • 14
0

use a simple forEach and assign new properties with bracket notation :

const currYear = (new Date()).getFullYear();
const lty = [currYear, currYear - 1, currYear - 2]

let result = {};

lty.forEach((e, i) => {
  result[e] = 0
})

console.log(result)
Taki
  • 17,320
  • 4
  • 26
  • 47
0

Enclose each key with brackets [] which are used for computed property names

You can use Object.assign as already suggested but if IE compatibility is required a basic loop will do too.

var currYear = 2018;
var lastThreeYearsArr = [currYear, currYear - 1, currYear - 2]

var obj = {};

for (var i = 0; i < lastThreeYearsArr.length; i++) {
    obj[lastThreeYearsArr[i]] = 0;
}

console.log(obj);
Nope
  • 22,147
  • 7
  • 47
  • 72