首页 新闻 会员 周边 捐助

JS前端怎么循环数据分组

0
悬赏园豆:40 [待解决问题]

test();
function test() {
let array = [];
array.push({zbz: '131624', yd: '201910'});
array.push({zbz: '146553', yd: '201911'});

array.push({zbz: '157479', yd: '202007'});
array.push({zbz: '153000', yd: '202008'});

array.push({zbz: '155775', yd: '202109'});
array.push({zbz: '39121', yd: '202110'});

array.push({zbz: '1234', yd: '20210710'});
array.push({zbz: '123', yd: '20210709'});
array.push({zbz: '123', yd: '20200710'});

let newArray = [];
for (let i = 0; i < array.length; i++) {
    let b = false;
    const obj = array[i];
    for (let i = 0; i < newArray.length; i++) {
        const obj1 = newArray[i]
        if (obj1.yd === obj.yd.substr(0, 4)) {
            obj1.zbz = parseFloat(obj.zbz) + parseFloat(obj1.zbz) + '';
            b = true;
            break;
        }
    }
    if (!b) {
        newArray.push({zbz: obj.zbz, yd: obj.yd.substr(0, 4)});
    }
}

console.log(newArray);

}

结果是这样

[{"zbz":"278177","yd":"2019"},{"zbz":"310602","yd":"2020"},{"zbz":"196253","yd":"2021"}]

理想的结果:

[{"zbz":"131624","zbz":"146553","yd":"2019"},{"zbz":"157479","zbz":"153000","yd":"2020"},{"zbz":"155775","zbz":"39121","yd":"2021"},]

小小白--的主页 小小白-- | 初学一级 | 园豆:162
提问于:2021-11-20 22:42
< >
分享
所有回答(1)
-1

你这种只能输出成一个字符串吧,没法成为一个json的

let array = [];
array.push({zbz: '131624', yd: '201910'});
array.push({zbz: '146553', yd: '201911'});

array.push({zbz: '157479', yd: '202007'});
array.push({zbz: '153000', yd: '202008'});

array.push({zbz: '155775', yd: '202109'});
array.push({zbz: '39121', yd: '202110'});

array.push({zbz: '1234', yd: '20210710'});
array.push({zbz: '123', yd: '20210709'});
array.push({zbz: '123', yd: '20200710'});

let newArray = [];
for (let i = 0; i < array.length; i++) {
    let b = false;
    const obj = array[i];
    let arr;
    for (let i = 0; i < newArray.length; i++) {
        const obj1 = newArray[i]
        if (obj1.yd === obj.yd.substr(0, 4)) {
            arr = obj1.li;
            b = true;
            break;
        }
    }
    if (!b) {
        arr = [];
        let newObj = {};
        newObj.li = arr;
        newObj.yd = obj.yd.substr(0, 4);
        newArray.push(newObj);
    }
    if (arr.length >= 2) {
        continue;
    }
    arr.push(obj.zbz);
}

let sArray = [];
for (let i = 0; i < newArray.length; i++) {
    const li = newArray[i].li
    let strli = [];
    for (let i = 0; i < li.length; i++) {
        strli.push('"zbz":"' + li[i] + '""');
    }
    sArray.push('{' + strli.join(',') + ',"yd":"' + newArray[i].yd + '"}')
}

let result = '[' + sArray.join(',') + ']';

console.log(result);
昵称要矢 | 园豆:202 (菜鸟二级) | 2021-11-22 00:03
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册