简体   繁体   English

Javascript 函数:使用变量而不是单个值

[英]Javascript Function: Use Variable instead of single Values

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?我必须做出哪些改变?

Define the bri property as an array of strings.bri属性定义为字符串数组。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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