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

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

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


当前回答

我想发表评论,但我没有必要的声誉。对马克西姆·库兹敏(Maxim Kuzmin)的答案进行了一个小改进,使其更有效:

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

解释

我们不是在每次迭代时将整个结果一遍又一遍地展开,而是仅在实际有值要插入时才将结果追加到数组。

其他回答

使用Array.prototype.filter:

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

与顶部答案相同的方法,使用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;
  }, []);
}

使用reduce,你可以在一个数组中做到这一点。函数原型。这将从数组中获取所有偶数。

Var arr = [1,2,3,4,5,6,7,8]; Var BRR = arr。Reduce ((c, n) => { 如果(n % 2 !== 0) { 返回c; } c.push (n); 返回c; },[]); . getelementbyid(“mypre”)。innerHTML = brr.toString(); <h1>获取所有偶数</h1> <pre id="mypre"> </pre>

您可以使用相同的方法并将其泛化到您的对象,如下所示。

var arr = options.reduce(function(c,n){
  if(somecondition) {return c;}
  c.push(n);
  return c;
}, []);

Arr现在将包含筛选过的对象。

你应该使用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;
}, []);

直接使用.reduce可能很难阅读,所以我建议创建一个生成reducer的函数:

function mapfilter(mapper) {
  return (acc, val) => {
    const mapped = mapper(val);
    if (mapped !== false)
      acc.push(mapped);
    return acc;
  };
}

像这样使用它:

const words = "Map and filter an array #javascript #arrays";
const tags = words.split(' ')
  .reduce(mapfilter(word => word.startsWith('#') && word.slice(1)), []);
console.log(tags);  // ['javascript', 'arrays'];