数组结构转为对象?

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.2k
6 个回答
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

let obj = {};

arr.forEach(item => {
    let { num, text, quantity } = item;
    if (!obj[num]) {
        obj[num] = [];
    }
    obj[num].push({ answer: text, quantity });
});

image.png

const result = {};

for (const item of data) {
  const { num, text, quantity } = item;
  
  if (result[num]) {
    result[num].push({ answer: text, quantity });
  } else {
    result[num] = [{ answer: text, quantity }];
  }
}
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 },
];

const arr2Obj = (array) => {
  let result = {};
  array.forEach(({num, text, quantity})=>{
    if(result[num] === undefined){
      result[num] = []
    }

    result[num] = [...result[num], { text, quantity }];
  })

  return result;
};

const result = arr2Obj(arr);
console.log(result);

非面试的话建议使用lodash

import _ from 'lodash';
const arr = [
  { num: '2', text: 'aaa', quantity: 1 },
  { num: '1', text: 'bbb', quantity: 2 },
  { num: '2', text: 'ccc', quantity: 3 },
  { num: '2', text: 'ddd', quantity: 1 },
  { num: '1', text: 'eee', quantity: 3 },
  { num: '1', text: 'eee', quantity: 2 },
];

const res = _.groupBy(arr, 'quantity');

换个reduce写法

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 arr1 = arr.reduce((prev,curr) => {
    let {num,text,quantity} = curr
    if (!prev[num]) {
        prev[num] = []
    }
    prev[num].push({
        text,
        quantity
    })
    return prev
},{})
console.log(arr1)

image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏