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

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

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


当前回答

我用以下几点优化了答案:

重写if (cond) {stmt;}作为cond && stmt; 使用ES6箭头函数

我将给出两个解决方案,一个使用forEach,另一个使用reduce:

解决方案1:使用forEach

该解决方案通过使用forEach遍历每个元素来实现。然后,在forEach循环的主体中,我们有条件作为过滤器,它决定我们是否要向结果数组追加一些内容。

Const选项= [ {name: 'One', assigned: true}, {name: 'Two',赋值:false}, {name: 'Three',赋值:true}, ]; Const reduced = []; 选项。forEach(o => { O.assigned && reduced。push({name: o.name, newProperty: 'Foo'}); }); console.log(减少);

解决方案2:使用reduce

这个解决方案使用array. prototype.reduce而不是forEach来迭代数组。它认识到这样一个事实,即reduce具有内置的初始化式和循环机制。除此之外,该解决方案与forEach解决方案或多或少是相同的,因此,区别在于修饰语法。

Const选项= [ {name: 'One', assigned: true}, {name: 'Two',赋值:false}, {name: 'Three',赋值:true}, ]; Const reduced = options。Reduce ((a, o) => { o.assigned && a.push({name: o.name, newProperty: 'Foo'}); 返回一个; }, []); console.log(减少);

我让你来决定采用哪种解决方案。

其他回答

你可以使用数组。Reduce带有箭头的函数是一行代码

Const选项= [ {name: 'One', assigned: true}, {name: 'Two',赋值:false}, {name: 'Three',赋值:true}, ]; Const reduced = options。Reduce ((result, option) =>选项。分配?结果。concat({name: option.name, newProperty: 'Foo'}): result, []); . getelementbyid(“输出”)。innerHTML = JSON.stringify(简化); <h1>仅分配选项</h1> <pre id="output"> </pre> .

使用Array.prototype.filter:

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

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

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

嘿,我刚刚在这个项目上工作,想在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);

直接使用.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'];