猿问

如何把对象数组进行切割,变成四个为一组的对象数组

eg:let arr = [{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3}];
如何让数组arr得到这个结果[{[{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3}]},{[{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3}]},{[{a:1,b:2,c:3},{},{},{}]}];
刚开始是9,转换成4个一组,不足的用{}空对象补全?

Helenr
浏览 485回答 3
3回答

拉风的咖菲猫

想要几个为一组就把sliceNum改为几~~&nbsp; &nbsp; const arr =&nbsp; [{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3}]&nbsp; &nbsp; const len = arr.length&nbsp; &nbsp; let result = []&nbsp; &nbsp; const sliceNum = 4&nbsp; &nbsp; for(let i = 0; i < len / sliceNum; i++){&nbsp; &nbsp; &nbsp; &nbsp; result.push(arr.slice(i * sliceNum, (i+1) * sliceNum))&nbsp; &nbsp; }&nbsp; &nbsp; for(let j = 0; j < (sliceNum - len % sliceNum); j++) {&nbsp; &nbsp; &nbsp; &nbsp; result[result.length - 1].push({})&nbsp; &nbsp; }&nbsp; &nbsp; console.log(result)

小怪兽爱吃肉

let arr = [{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3}];var result = new Array()for (var i = 0; i < arr.length; i += 4){&nbsp; var tmp = new Array()&nbsp; for (var j = 0; j < 4; j++){&nbsp; &nbsp; if ((i+j) >= arr.length) {&nbsp; &nbsp; &nbsp; tmp.push({})&nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; }&nbsp; &nbsp; tmp.push(arr[i+j])&nbsp; }&nbsp; result.push({tmp})}console.log(result)

宝慕林4294392

你输出结果对象部分没有键名啊。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答