我有一个对象数组,我想对其进行迭代以生成一个新的过滤数组。同时,我还需要根据参数从新数组中过滤出一些对象。我试着这样做:

function renderOptions(options) {
    return options.map(function (option) {
        if (!option.assigned) {
            return (someNewObject);
        }
    });   
}

这是个好方法吗?有没有更好的方法?我愿意使用任何库,如lodash。


当前回答

我把这些伟大的答案隐藏在效用函数中,我想分享它们:

示例:只过滤奇数并增加它

如(1、2、3、4、5)过滤器- >(1、3、5)地图——>(2、4、6)

通常过滤器和映射都是这样

const inputArray = [1, 2, 3, 4, 5];
const filterOddPlusOne = inputArray.filter((item) => item % 2).map((item) => item + 1); // [ 2, 4, 6 ]

使用减少

const filterMap = <TSource, TTarget>(
  items: TSource[],
  filterFn: (item: TSource) => boolean,
  mapFn: (item: TSource) => TTarget
) =>
  items.reduce((acc, cur): TTarget[] => {
    if (filterFn(cur)) return [...acc, mapFn(cur)];
    return acc;
  }, [] as TTarget[]);

使用flatMap

const filterMap = <TSource, TTarget>(
  items: TSource[],
  filterFn: (item: TSource) => boolean,
  mapFn: (item: TSource) => TTarget
) => items.flatMap((item) => (filterFn(item) ? [mapFn(item)] : []));

用法(reduce和flatMap解决方案相同):

const inputArray = [1, 2, 3, 4, 5];
const filterOddPlusOne = filterMap(
  inputArray,
  (item) => item % 2, // Filter only odd numbers
  (item) => item + 1 // Increment each number
); // [ 2, 4, 6 ]

JavaScript版本

上面的代码是TypeScript的,但是问题问的是JavaScript。所以,我已经为你删除了所有的泛型和类型:

const filterMap = (items, filterFn, mapFn) =>
  items.reduce((acc, cur) => {
    if (filterFn(cur)) return [...acc, mapFn(cur)];
    return acc;
  }, []);
const filterMap = (items, filterFn, mapFn) =>
  items.flatMap((item) => (filterFn(item) ? [mapFn(item)] : []));

其他回答

嘿,我刚刚在这个项目上工作,想在MDN文档中分享我基于Array.prototype.flatMap()的解决方案:

const places=[{latitude:40,longitude:1},{latitude:41,longitude:2},{latitude:44,longitude:2},{latitude:NaN,longitude:NaN},{latitude:45,longitude:4},{latitude:48,longitude:3},{latitude:44,longitude:5},{latitude:39,longitude:13},{latitude:40,longitude:8},{latitude:38,longitude:4}]; let items = places?.map((place) => [{ latitude: (place.latitude), longitude: (place.longitude), }, ]); console.log("Items: ", items); //Remove elements with NaN latitude and longitude let newItems = places?.flatMap((o) => Number(o.longitude, o.latitude) ? { lng: Number(o.longitude), lat: Number(o.latitude) } : [] ); console.log("Coordinates after NaN values removed: ", newItems);

你应该使用Array。减少这个。

Var选项= [ {name: 'One', assigned: true}, {name: 'Two',赋值:false}, {name: 'Three',赋值:true}, ]; Var减少=选项。减少(函数(筛选,选项){ If (option.assigned) { var someenewvalue = {name: option.name, newProperty: 'Foo'} filtered.push (someNewValue); } 返回过滤; },[]); . getelementbyid(“输出”)。innerHTML = JSON.stringify(简化); <h1>仅分配选项</h1> <pre id="output"> </pre> .


或者,减速器可以是一个纯函数,就像这样

var reduced = options.reduce(function(result, option) {
  if (option.assigned) {
    return result.concat({
      name: option.name,
      newProperty: 'Foo'
    });
  }
  return result;
}, []);

与顶部答案相同的方法,使用Array.prototype.reduce(),但使用了更新的ES6语法和TypeScript类型,作为通用实用函数:

function filterThenMap<T>(l: T[], predicate: (el: T) => boolean, transform: (el: T) => T) {
  return l.reduce((res: T[], el) => {
    if (predicate(el)) {
      res.push(transform(el));
    }
    return res;
  }, []);
}

这里有一行使用ES6花哨扩展语法的简化!

Var选项= [ {name: 'One', assigned: true}, {name: 'Two',赋值:false}, {name: 'Three',赋值:true}, ]; Const filtered = options .reduce((result, {name, assigned}) =>[…]结果,…分配?[name]: []], []); console.log(过滤);

在ES6中,你可以做的很短:

选项。过滤器(opt => !opt.assigned)。目录(opt => someNewObject)