Как сделать из обьекта массив всех комбинаций?
У меня есть обьект к примеру
let a = {
"color": "blue,white, black",
"size": "M,L",
"length": "23,44"
}
Мне нужен массив со всеми комбинациями:
[
{"color": "blue", "size": "M", "length": "23"},
{"color": "blue", "size": "M", "length": "44"},
{"color": "blue", "size": "L", "length": "23"},
{"color": "blue", "size": "L", "length": "44"},
{"color": "white", "size": "M", "length": "23"},
]
Я пробую сделать это через цикл:
let arr = [];
for (const obj in a) {
const key = obj;
const aRR = a[key].split(',')
const object = {};
for (const item of aRR) {
object[key] = item;
arr.push({[obj]: item})
}
}
Ответы (1 шт):
Автор решения: Nikita Galadiy
→ Ссылка
Как вариант - можно рекурсивно пройтись по ключам объекта, итерируя его значения
const A = {
color: "blue,white,black",
size: "M,L",
length: "23,44"
};
function getVariants(from) {
const result = [];
const buffer = {};
const keys = Object.keys(from);
const next = (index = 0) => {
const current = keys[index];
for (const item of from[current].split(",")) {
buffer[current] = item;
if (index + 1 === keys.length) {
result.push({ ...buffer });
} else {
next(index + 1);
}
}
};
next();
return result;
}
const variants = getVariants(A);
console.log(variants);