数组结构转为对象?

作者站长头像
站长
· 阅读数 24
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

回复
1个回答
avatar
test
2024-06-26
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);

answer image

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容