let arr = [
{
"productAttributeId": 2,
"value": "白色",
"name": "color"
},{
"productAttributeId": 2,
"value": "黑色",
"name": "color"
},{
"productAttributeId": 5,
"value": "M",
"name": "size"
},{
"productAttributeId": 5,
"value": "X",
"name": "size"
},{
"productAttributeId": 5,
"value": "L",
"name": "size"
},
]
function getMultidimensional(arr) {
const data = {};
arr.forEach((item) => {
const list = data[item.name] || [];
list.push(item);
data[item.name] = list;
});
return Object.keys(data).map((key) => data[key]);
}
function getCartesianProduct(array) {
if (!Array.isArray(array)) return [[]];
array = array.filter((_) => _.length > 0);
if (array.length < 2) return array;
const list1 = array.splice(0, 1)[0];
const list2 = array.splice(0, 1)[0];
const list = [];
list1.forEach((_list1) => {
list2.forEach((_list2) => {
if (_list1.name) {
list.push({
[_list1.name]: _list1.value,
[_list2.name]: _list2.value,
});
} else {
list.push({
..._list1,
[_list2.name]: _list2.value,
});
}
});
});
return getCartesianProduct([list].concat(array));
}
const list = getCartesianProduct(getMultidimensional(arr))
console.log(list)
