1. let arr = [
    2. {
    3. "productAttributeId": 2,
    4. "value": "白色",
    5. "name": "color"
    6. },{
    7. "productAttributeId": 2,
    8. "value": "黑色",
    9. "name": "color"
    10. },{
    11. "productAttributeId": 5,
    12. "value": "M",
    13. "name": "size"
    14. },{
    15. "productAttributeId": 5,
    16. "value": "X",
    17. "name": "size"
    18. },{
    19. "productAttributeId": 5,
    20. "value": "L",
    21. "name": "size"
    22. },
    23. ]
    24. // 转换成多维数组
    25. function getMultidimensional(arr) {
    26. const data = {};
    27. arr.forEach((item) => {
    28. const list = data[item.name] || [];
    29. list.push(item);
    30. data[item.name] = list;
    31. });
    32. return Object.keys(data).map((key) => data[key]);
    33. }
    34. // 求笛卡尔积
    35. function getCartesianProduct(array) {
    36. if (!Array.isArray(array)) return [[]]; // 判断数组
    37. array = array.filter((_) => _.length > 0); // 清除数组里面的空数组
    38. if (array.length < 2) return array; // 数组少于两个 GG
    39. const list1 = array.splice(0, 1)[0]; // 取出第一个
    40. const list2 = array.splice(0, 1)[0]; // 取出第二个
    41. const list = [];
    42. list1.forEach((_list1) => {
    43. list2.forEach((_list2) => {
    44. if (_list1.name) {
    45. list.push({
    46. [_list1.name]: _list1.value,
    47. [_list2.name]: _list2.value,
    48. });
    49. } else {
    50. list.push({
    51. ..._list1,
    52. [_list2.name]: _list2.value,
    53. });
    54. }
    55. });
    56. });
    57. return getCartesianProduct([list].concat(array));
    58. }
    59. const list = getCartesianProduct(getMultidimensional(arr))
    60. console.log(list)

    image.png