尝试进行过滤时如何正确构造reducer?

时间:2017-03-30 18:40:42

标签: javascript arrays redux lodash

查看https://lodash.com/docs/4.17.4#filter

我有一个对象数组,每个对象看起来像这样:

{
  id: 10005,
  title: 'Brooklyn Bridge by Night',
  author: 'Charles Gooding',
  takenOn: 'some date',
  description: 'Photo of the Brooklyn Bridge at night.  Taken from somewhere I am just making this up to be honest.',
  cameraId: 301,
  // some other stuff
}

我正在尝试快速过滤,这是FILTER_RESULTS的减速器。如何避免使用构建的数组?

case 'FILTER_RESULTS':
  const results = [];
  state.photos.map((a) => {
    Object.keys(a).forEach((b) => {
      if (a[b].toLowerCase().includes(action.value.toLowerCase())) {
        results.push(a); // also a question on this one
      }
    });
    return results;
  });
  return {
    ...state,
    state.photosFilter: results
  }

另外,如何确保我推入结果的对象是唯一的?感谢

1 个答案:

答案 0 :(得分:1)

做小而窄的功能;它们易于理解和结合。

function includesAttributes(thing, target) {
   return _.some(Object.keys(thing), 
                 (key) => thing[key].toLowerCase().includes(target.toLowerCase()));
}

然后

case 'FILTER_RESULTS':
  return state.photos.filter((record) => includesAttribute(record, action.value));