Javascript 如何将数组转换为对象?请
我想转换以下数组Javascript 如何将数组转换为对象?请,javascript,Javascript,我想转换以下数组 input : [["A","B"],["C","D"],["F","G"]] It can be one or two arrays [["A","B"]] or [["A","B"],["C","D"]] or [["
input : [["A","B"],["C","D"],["F","G"]]
It can be one or two arrays
[["A","B"]] or [["A","B"],["C","D"]] or [["A","B"],["C","D"],["F","G"]]
预期输出笛卡尔:
[{"custom1" : "A", "custom2" : "C", "custom3" : "F"},
{"custom1" : "A", "custom2" : "C", "custom3" : "G"},
{"custom1" : "A", "custom2" : "D", "custom3" : "F"},
{"custom1" : "A", "custom2" : "D", "custom3" : "G"},
{"custom1" : "B", "custom2" : "C", "custom3" : "F"},
{"custom1" : "B", "custom2" : "C", "custom3" : "G"},
{"custom1" : "B", "custom2" : "D", "custom3" : "F"},
{"custom1" : "B", "custom2" : "D", "custom3" : "G"}]
const items = [["A","B"],["C","D"],["F","G"]]
items.reduce((a, b) => a.reduce((r, v) => r.concat(b.map((w) => [].concat(v, w))), []));
result : [[],[],[].......]
使用此方法
var arr=[[“A”、“B”]、[“C”、“D”]、[“F”、“G”];
var obj=Object.assign({},arr);
console.log(obj)
您可以使用和将最终结果转换为所需的对象
items
.reduce((a, b) => a.reduce((r, v) => r.concat(b.map((w) => [].concat(v, w))), []))
.map((v) => Object.fromEntries(v.map((sv, sk) => [`custom${sk + 1}`, sv])));
我建议使用递归来实现这一点,它更具可读性
let items = [["A","B"],["C","D"],["E","F"]];
let ans = []
function permutations(index, s) {
if (index >= items.length) {
ans.push(s);
return;
}
for (let i=0; i < items[index].length; i++){
permutations(index+1, s+items[index][i]);
}
}
permutations(0, "");
console.log(ans);
let items=[[“A”、“B”]、[“C”、“D”]、[“E”、“F”];
让ans=[]
函数置换(索引,s){
如果(索引>=items.length){
ans.push(s);
返回;
}
for(设i=0;i