gpt4 book ai didi

javascript - 在 json 中组合两个数组

转载 作者:行者123 更新时间:2023-11-28 17:38:50 25 4
gpt4 key购买 nike

输入:

"options": [
{
"name": "Color",
"values": [
"Blue",
"Black"
]
},
{
"name": "Size",
"values": [
"Small",
"Large"
]
}
]

Output: "variants": [
{
"option1": "Blue",
"option2": "Small"
},
{
"option1": "Blue",
"option2": "Large"
},
{
"option1": "Black",
"option2": "Small"
},
{
"option1": "Black",
"option2": "Large"
}
]

如何使用递归解决这个问题?选项数组可以包含多个名称,我需要显示上面的内容。我猜可以使用笛卡尔积来完成

最佳答案

您可以采用迭代和递归方法来获取所有选项组合。

function getCombinations(array) {

function iter(i, temp) {
if (i === array.length) {
result.push(temp.reduce(function (o, v, i) {
o['option' + (i + 1)] = v;
return o;
}, {}));
return;
}
array[i].values.forEach(function (a) {
iter(i + 1, temp.concat(a));
});
}

var result = [];
iter(0, []);
return result;
}

var options = [{ name: "Color", values: ["Blue", "Black"] }, { name: "Size", values: ["155", "159"] }, { name: 'Material', values: ['Sand', 'Clay', 'Mud'] }],
variants = getCombinations(options);

console.log(variants);
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES6

function getCombinations(array) {

function iter(i, temp) {
if (i === array.length) {
result.push(temp);
return;
}
array[i].values.forEach(a => iter(i + 1, Object.assign({}, temp, { ['option' + (i + 1)]: a })));
}

var result = [];
iter(0, {});
return result;
}

var options = [{ name: "Color", values: ["Blue", "Black"] }, { name: "Size", values: ["155", "159"] }, { name: 'Material', values: ['Sand', 'Clay', 'Mud'] }],
variants = getCombinations(options);

console.log(variants);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 在 json 中组合两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48440835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com