将函数应用于在另一个数组中匹配的键匹配的值



i有一个形式。值如下

 form.value = {
  "to_date": "2019-03-21T05:00:00.000Z",
  "from_date": "2019-03-13T05:00:00.000Z",
  "is_form": ""
  "errors":""
}

我的数组如下

filterArray = [
  "from_date",
  "to_date"
]

我想在form.value对象键上迭代并在匹配过滤器数组中匹配的键的值上应用功能(converFormat())如下所示

  form.value = {
  "to_date": "2019-03-21T05:00:00.000Z",       // apply a function() over value since key is present in the filterArray
  "from_date": "2019-03-13T05:00:00.000Z",     // apply a function() over value since key is present in the filterArray
  "is_form": ""                               
  "errors":""                                  
}
Object.keys(form.value).filter(key => filterArray.includes(key)).forEach(key => {
  form.value[key] = myFunction(form.value[key])
})
// Or if you want to cache the value in some other variable
const customFormValue = {
  ...form.value,
  ...Object.keys(form.value)
    .filter(key => filterArray.includes(key))
    .reduce(
      (pr, curr) => ({
        ...pr,
        [curr]: myFunction(form.value[curr])
      }),
      {}
    )
};

最新更新