0

I'm not sure if it's possible or not. So here I'm looking for an answer.

Is there any way to declare an object like:

var objectName = {
    key1      : 'value1',

    key2,key3 : 'value2;
}

I'm trying to combine key2 and key3 together.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Sanjay Joshi
  • 2,036
  • 6
  • 33
  • 48

2 Answers2

0

If you don't want to assign the values like Patric Roberts says, create an array of keys and set the same value to those keys like so:

var obj = {};
obj['key1'] = 1;

// Array of keys
var arrayOfKeys = ['key2','key3','key4'];
// Common value for keys in array
var val = 2;

// Iterate the array
for(var k in arrayOfKeys) {
  obj[arrayOfKeys[k]] = val;
}
console.log(obj);

You can also check this answer

kapantzak
  • 11,610
  • 4
  • 39
  • 61
0

You could use a slightly different approach, which will work on primitive values, too, by adding an object for keeping the same reference to different keys in the array. For example, you have a value object, like

temp = {
    value: 42
}

and an array, like

object = {
    key2: temp,
    key3: temp
}

then you can use the keys independently for the value of the referenced object.

To change the value, you need to address it with

object.key2.value = 2000;
console.log(object.key3.value); // 2000
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392