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

时间:2019-03-05 22:14:05

标签: arrays angular typescript object angular-reactive-forms

我有一个form.value如下

 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":""                                  
}

1 个答案:

答案 0 :(得分:0)

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])
      }),
      {}
    )
};