根据对象数组过滤对象值

时间:2016-10-28 14:39:35

标签: javascript underscore.js

我有两个变量,一个是POST数据的对象(两个复选框和一个电子邮件输入):

{ _csrf: 'oWNyWOhgvRyEGafTTOO1Yiv78BfG0D1n+DLVA=',
  activated: 'true',
  notify: 'true',
  email: 'test@gmail.com' }

另一个是配置模板文件,用于生成表单(POST数据来自):

[{ displayName: 'Activated',
  name: 'activated',
  description: '',
  type: 'Boolean',
  defaults: { value: false, readOnly: false } }
{ displayName: 'Send Notifications',
  name: 'notify',
  description: '',
  type: 'Boolean',
  defaults: { value: false, readOnly: false } }
{ displayName: 'Notification Email',
  name: 'email',
  description: '',
  type: 'String:Email',
  defaults: { value: '', readOnly: false } }]

我需要将第一个对象过滤到key: value对,其中键存在于数组中(name: 'key')。

我正在尝试使用_.filter_.find,但是到目前为止我写的内容已经成功过滤了对象,但只返回值的数组,没有键:

const update = _.filter(req.body, function(val, name){
  return _.find(_module.config, function(param){
    return param.name == name;
  });
});

// update = [ 'true', 'true', 'test@gmail.com' ]

最后,我的最后一个问题是,如果未选中其中一个复选框,则POST数据中不存在该键的值。理想情况下,过滤器函数还应设置它在配置模板中找到的任何值,但不能将数据设置为false

1 个答案:

答案 0 :(得分:1)

.reduce()数组并从原始对象中获取与项目名称匹配的属性:

function filterPropsByArray(arr, obj) {
  return arr.reduce(function(o, item) {
    obj.hasOwnProperty(item.name) && (o[item.name] = obj[item.name]); // if the name exists in the original object, assign it
    return o;
  }, {});
} 

var obj = { _csrf: 'oWNyWOhgvRyEGafTTOO1Yiv78BfG0D1n+DLVA=',
  activated: 'true',
  notify: 'true',
  email: 'test@gmail.com' };

var arr = [{ displayName: 'Activated',
  name: 'activated',
  description: '',
  type: 'Boolean',
  defaults: { value: false, readOnly: false } },
{ displayName: 'Send Notifications',
  name: 'notify',
  description: '',
  type: 'Boolean',
  defaults: { value: false, readOnly: false } },
{ displayName: 'Notification Email',
  name: 'email',
  description: '',
  type: 'String:Email',
  defaults: { value: '', readOnly: false } }];

var result = filterPropsByArray(arr, obj); 

console.log(result);