Home > Net >  Javascript Function: Use Variable instead of single Values
Javascript Function: Use Variable instead of single Values

Time:12-15

I found here a script. It works fine. But now, I want to use a Variable instead of single values.

Here the original script:

const customData = {
   "func":"bri",
   "oid":"ID",
   "onVal":1,
   "offVal":0,
   "...":"..."
}

const getSubset = (obj, ...keys) => keys.reduce((a, c) => ({ ...a, [c]: obj[c] }), {});
const Light.bri = getSubset(customData, "oid", "onVal", "offVal");

Result (OK):

  bri: {
    offVal: 0,
    oid: "objekt-ID",
    onVal: 1
  },

Now I want to do define the keys in a variable, ideally as a object. But this do not work.

const params = {bri: "oid, onVal, offVal"};
const Light.bri = getSubset(customData, params.bri);

Result (NOK):

  bri: {
    oid, onVal, offVal: undefined
  },
  description: "Deckenspots"
}

what changes do I have to make?

CodePudding user response:

Define the bri property as an array of strings. That way you can use the spread syntax (...) to pass the strings as individual arguments.

const params = {bri: ["oid", "onVal", "offVal"]}; // bri is now an array.
const Light.bri = getSubset(customData, ...params.bri); // Notice the ... before params.bri
  • Related