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

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

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


当前回答

在某些情况下,使用forEach不是更容易(或同样容易)吗

Var选项= [ {name: 'One', assigned: true}, {name: 'Two',赋值:false}, {name: 'Three',赋值:true}, ]; Var减小= [] options.forEach(功能(选项){ If (option.assigned) { var someenewvalue = {name: option.name, newProperty: 'Foo'} reduced.push (someNewValue); } }); . getelementbyid(“输出”)。innerHTML = JSON.stringify(简化); <h1>仅分配选项</h1> <pre id="output"> </pre> .

但是,如果有一个malter()或fap()函数组合映射和过滤器函数就更好了。它将像过滤器一样工作,除了返回true或false之外,它将返回任何对象或null/undefined。

其他回答

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

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

用减法,卢克!

function renderOptions(options) {
    return options.reduce(function (res, option) {
        if (!option.assigned) {
            res.push(someNewObject);
        }
        return res;
    }, []);   
}

你可以使用数组。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> .

我想发表评论,但我没有必要的声誉。对马克西姆·库兹敏(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);
    });   
}