js 数组对象根据多个key值进行分类

const list = [
  { id: 1, name: "手机1", orderNo: "6901443393268", sku: "51095BKR" },
  { id: 2, name: "手机2", orderNo: "6901443393262", sku: "51095BBQ" },
  { id: 3, name: "手机3", orderNo: "6901443393262", sku: "51095BKR" },
  { id: 4, name: "手机2", orderNo: "6901443393262", sku: "51095BKR" },
  { id: 5, name: "手机5", orderNo: "6901443393268", sku: "51095BBQ" },
  { id: 6, name: "手机3", orderNo: "6901443393262", sku: "51095BKR" },
  { id: 7, name: "手机7", orderNo: "6901443393262", sku: "51095BKR" },
  { id: 8, name: "手机5", orderNo: "6901443393268", sku: "51095BBQ" },
  { id: 9, name: "手机5", orderNo: "6901443393268", sku: "51095BBQ" },
  { id: 10, name: "手机5", orderNo: "6901443393268", sku: "51095BBQ" },
  { id: 11, name: "手机5", orderNo: "6901443393268", sku: "51095BBQ" },
];

/**
 * 数组对象根据多个key值进行分类
 * @param {*} arr
 * @param {*} key
 */
const handleArraySortByKey = (arr, key) => {
  const obj = {};
  arr.forEach((item) => {
    let value = Array.isArray(key)
      ? key.map((v) => item[v]).join()
      : item[key];
    obj[value] ? obj[value].push(item) : (obj[value] = [item]);
  });
  return Object.keys(obj).map((item) => obj[item]);
};
console.log(handleArraySortByKey(list, ["orderNo", "sku"]));

 

 

posted @ 2022-11-14 17:19  浮生如梦似离殇  阅读(1084)  评论(0编辑  收藏  举报