gpt4 book ai didi

javascript - 在对象内组合数组的元素

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:30:27 26 4
gpt4 key购买 nike

trialObject : {
'color': ['red','blue'],
'size': ['s','m'],
'material': ['cotton']
}

// RECURSION FUNCTION TO MAKE COMBINATIONS

makeObjectVariants(selected){

let key = Object.keys(selected)
if(Object.keys(selected).length === 1){
return selected[key[0]];
} else {
var result = [];
var currentArray = selected[key[0]]
delete selected[key[0]]
var restObjects = this.makeObjectVariants(selected) // call function again

for(var i = 0; i < restObjects.length; i++){
for (var j = 0; j < currentArray.length; j++) {
result.push([restObjects[i] +','+ currentArray[j]]);
}
}
return result; // resultant array
}
}

// OUTPUT
0:["cotton,s,red"]
1:["cotton,s,blue"]
2:["cotton,m,red"]
3:["cotton,m,blue"]

// EXPECTED OUTPUT
[{'material':cotton,'size':s,'color':red},...]

我希望输出包含键值对,以便可以识别数组元素属于哪个组。

我在向生成的元素添加键时遇到问题,因为我无法跟踪对象键

最佳答案

如果您可以使用 ES6(默认参数、扩展运算符、箭头函数,...),则以下代码可以完成这项工作:

var trialObject  = {
color: ['red','blue'],
size: ['s','m'],
material: ['cotton']
};

var result = buildCombinations(trialObject);

console.log(result);

function buildCombinations(trialObject , keys = Object.keys(trialObject ), keyIndex = 0 , subObj = {}, res = []) {
trialObject[keys[keyIndex]].forEach(element => {
subObj[keys[keyIndex]] = element;
keys[keyIndex + 1] ? buildCombinations(trialObject , keys, keyIndex + 1, subObj, res) : res.push({...subObj});
});
return res;
}

关于javascript - 在对象内组合数组的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48108413/

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