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"},]
你这种只能输出成一个字符串吧,没法成为一个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);