首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >根据对象数组过滤对象值

根据对象数组过滤对象值
EN

Stack Overflow用户
提问于 2016-10-28 22:39:35
回答 1查看 429关注 0票数 1

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

代码语言:javascript
运行
复制
{ _csrf: 'oWNyWOhgvRyEGafTTOO1Yiv78BfG0D1n+DLVA=',
  activated: 'true',
  notify: 'true',
  email: 'test@gmail.com' }

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

代码语言:javascript
运行
复制
[{ 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 } }]

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

代码语言:javascript
运行
复制
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数据中就不会出现该键的值。理想情况下,filter函数还应该将它在配置模板中找到的任何值设置为false

EN

回答 1

Stack Overflow用户

发布于 2016-10-28 22:45:51

对数组执行.reduce()操作,并从原始对象中仅获取与项的名称匹配的属性:

代码语言:javascript
运行
复制
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);

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40307504

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档