数组结构转为对象?-灵析社区

三千米的偷感

let arr = [{num:'2', text: 'aaa', quantity: 1}, {num: '1', text: 'bbb', quantity: 2}, {num: '2', text: 'ccc', quantity: 1}, {num: '2', text: 'ddd', quantity: 1}, {num: '1', text: 'eee', quantity: 1}] 转为 let obj = { 1:[{answer:'bbb',quantity:2},{answer:'eee',quantity:1}], 2:[{answer:'aaa',quantity:1},{answer:'ccc',quantity:1},{answer:'ddd',quantity:1}] } 用num作为key

阅读量:208

点赞量:12

问AI
let arr = [ { num: '2', text: 'aaa', quantity: 1 }, { num: '1', text: 'bbb', quantity: 2 }, { num: '2', text: 'ccc', quantity: 1 }, { num: '2', text: 'ddd', quantity: 1 }, { num: '1', text: 'eee', quantity: 1 } ]; let obj = {}; // 遍历数组并将条目按照num属性值分组 arr.forEach(item => { const num = item.num; const answer = item.text; const quantity = item.quantity; if (!obj[num]) { obj[num] = []; } obj[num].push({ answer, quantity }); }); // 输出结果 console.log(obj); "image.png" (https://wmprod.oss-cn-shanghai.aliyuncs.com/images/20241224/9b03c291620c9537cbfe76e737a7904a.png)