taile
taile

Reputation: 2776

Dynamically set multiple object properties using variable

I wanna set multiple object property with the same value.

const SHOW_PAYMENT_DIALOG = 'SHOW_PAYMENT_DIALOG';
const SHOW_BUSINESS_DIALOG = 'SHOW_BUSINESS_DIALOG';

const handler = (state, payload) => {
    return {
        ...state,
        data: payload
    };
  };

const object = {
  [SHOW_BUSINESS_DIALOG]: handler,
  [SHOW_PAYMENT_DIALOG]: handler,
};

As above example, I have to manually assign handler for 2 property SHOW_BUSINESS_DIALOG & SHOW_PAYMENT_DIALOG

Is there anyway to set it quickly on the fly by js api but no need to introduce a new function to handle that like

const object = {
      [SHOW_BUSINESS_DIALOG, SHOW_PAYMENT_DIALOG]: handler,
    };

Upvotes: 0

Views: 432

Answers (2)

Nick Parsons
Nick Parsons

Reputation: 50724

You could use Object.fromEntries() with .map() if you're okay with having the same reference to handler for each value... (the snippet console output shows how the handler method is the same reference for each value, that's why it looks a little strange):

const SHOW_PAYMENT_DIALOG = 'SHOW_PAYMENT_DIALOG';
const SHOW_BUSINESS_DIALOG = 'SHOW_BUSINESS_DIALOG';

const handler = (state, payload) => {
  return {
    ...state,
    data: payload
  };
};

const keys = [SHOW_PAYMENT_DIALOG, SHOW_BUSINESS_DIALOG];
const object = Object.fromEntries(keys.map(k => [k, handler]));

console.log(object);

Please note that .fromEntries() is currently in draft mode, however, I think a generic if statement accompanied with a Set (using .has()) would be better for this case than using an object:

const SHOW_PAYMENT_DIALOG = 'SHOW_PAYMENT_DIALOG';
const SHOW_BUSINESS_DIALOG = 'SHOW_BUSINESS_DIALOG';

const handler = (state, payload) => {
  return {
    ...state,
    data: payload
  };
};

const get_handler = key => {
  const keys = new Set([SHOW_PAYMENT_DIALOG, SHOW_BUSINESS_DIALOG]);
  if(keys.has(key))
    return handler;
}

console.log(get_handler(SHOW_BUSINESS_DIALOG)); // hanlder
console.log(get_handler("foo")); // undefined

Upvotes: 2

Code Maniac
Code Maniac

Reputation: 37755

You can create a generic function and pass an array of key and loop through keyArr and place value for each key

const SHOW_PAYMENT_DIALOG = 'SHOW_PAYMENT_DIALOG';
const SHOW_BUSINESS_DIALOG = 'SHOW_BUSINESS_DIALOG';

let value = "some value"
const object = { someKey: 'value'};

let dynamicSetValues = (keyArr, value) => {
  keyArr.forEach(key => {
    object[key] = value
  })
}

dynamicSetValues(['SHOW_PAYMENT_DIALOG','SHOW_BUSINESS_DIALOG'], value)

console.log(object)

Note:- this mutates original object, if you want immutability you can make a copy of object and place value on desired keys and return a new object every time from function

Upvotes: 1

Related Questions