简体   繁体   中英

JavaScript Object declaration by combining two different keys

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM