碎片时间学编程「81]:过滤匹配和未指定的值


碎片时间学编程「81]:过滤匹配和未指定的值

根据条件过滤对象数组,同时过滤掉未指定的键。

  • 使用Array.prototype.filter()根据谓词过滤数组fn,使其返回条件为真值的对象。
  • 在过滤后的数组上,用Array.prototype.map()返回新对象。
  • Array.prototype.reduce()过滤掉未作为keys参数提供的键。

JavaScript

const reducedFilter = (data, keys, fn) =>
  data.filter(fn).map(el =>
    keys.reduce((acc, key) => {
      acc[key] = el[key];
      return acc;
    }, {})
  );

示例:

const data = [
  {
    id: 1,
    name: 'john',
    age: 24
  },
  {
    id: 2,
    name: 'mike',
    age: 50
  }
];
reducedFilter(data, ['id', 'name'], item => item.age > 24);
// [{ id: 2, name: 'mike'}]

更多内容请访问我的网站:https://www.icoderoad.com

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章