猿问

怎么把数组中的有规律的多个对象合并成一个?

[{

    method:'fly',

    code:'1',

    count:1,

},{

    method:'fly',

    code:'1',

    count:2,

}]

[{

    method:'fly',

    code:'1',

    count:3,//count相加了

}]

自己实现了一个,不知道有么有bug,求指点


function mergeOrder(order) {

    return order.reduce((a, b) => {


        let flag = a.some((item, index) => {

            return item.method === b.method && item.code === b.code;

        });

        if (flag) {

            for (let item of a) {

                if (item.method === b.method && item.code === b.code) {

                    item.count += b.count;

                }

            }

        } else {

            a.push(b);

        }

        return a;

    }, [{

        method: '',

        code: '',

        count: 0

    }]);

}


料青山看我应如是
浏览 586回答 1
1回答

aluckdog

如下,result是你想要得到的数组:var result = [];var arr = [{&nbsp; &nbsp; method:'fly',&nbsp; &nbsp; code:'1',&nbsp; &nbsp; count:1,},{&nbsp; &nbsp; method:'fly',&nbsp; &nbsp; code:'1',&nbsp; &nbsp; count:2,}];for(var i =0; i< arr.length; i++){&nbsp; &nbsp; var isFind = false;&nbsp; &nbsp; for(var j =0 ; j< result.length; j++){&nbsp; &nbsp; &nbsp; &nbsp; if(arr[i].method === result[j].method &&&nbsp; arr[i].code === result[j].code){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result[j].count += arr[i].count;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; isFind = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; if(!isFind)&nbsp; &nbsp; &nbsp; result.push(arr[i]);}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答