Lucas Bueno Lucas Bueno - 1 year ago 66
Javascript Question

Set the same value for multiple identifiers in a Javascript Object

i have an object that stores a table for converting a json response in a user readeable text. The thing is, the same text applies for multiple json conditions.
I want to know if there's a way to set the same value for 2 different Id's in a object.
Like, instead of:

var msg = {
“error_code1”: “user_msg”,
“error_code2”: “user_msg”,

Something like this

var msg = {
“error_code1” && “error_code2": “user_msg”,

Is it possible?

Answer Source

First approach is using "getter" functions to reference the initial object:

var errorBindings = {
    'errorCode101': 'Unauthorized request',
    get 'errorCode102'() { return this.errorCode101; },
    get 'errorCode103'() { return this.errorCode101; },
    'errorCode104': 'All fields are required',
    get 'errorCode105'() { return this.errorCode104; },

console.log(errorBindings.errorCode103);  // "Unauthorized request"

Second approach is using an anonymous function with referencing properties from which we should borrow the needed value:

var messages = function(o) {
    o.errorCode101 = 'Authorization error!';
    o.errorCode102 = o.errorCode101;
    o.errorCode103 = o.errorCode101;
    o.errorCode104 = 'All fields are required';
    return o;

console.log(messages.errorCode101);  // "Authorization error!"
console.log(messages.errorCode103);  // "Authorization error!"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download