Javascript 生成多维对象的所有组合 问题
我想为一个类似模板的对象生成所有组合,该对象可以包含几个子对象,其中一些子对象将所需的输出定义为数组。这些孩子也可以生孩子(实际上没有限制) 示例输入 示例输出 问题: 将输入转换为输出的JavaScript函数是什么 尝试了什么? 我尝试从这个问题中获取原始函数,使其更符合ES,但当对象中有多个子对象时,这不起作用Javascript 生成多维对象的所有组合 问题,javascript,algorithm,object,Javascript,Algorithm,Object,我想为一个类似模板的对象生成所有组合,该对象可以包含几个子对象,其中一些子对象将所需的输出定义为数组。这些孩子也可以生孩子(实际上没有限制) 示例输入 示例输出 问题: 将输入转换为输出的JavaScript函数是什么 尝试了什么? 我尝试从这个问题中获取原始函数,使其更符合ES,但当对象中有多个子对象时,这不起作用 function combinations(input, keyIndex = 0, current = {}, result = []) { const keys = Obj
function combinations(input, keyIndex = 0, current = {}, result = []) {
const keys = Object.keys(input)
const key = keys[keyIndex]
const values = input[key]
for (const index in values) {
current[key] = values[index]
if (keyIndex + 1 < keys.length) {
combinations(input, keyIndex + 1, current, result)
} else {
result.push(JSON.parse(JSON.stringify(current)))
}
}
return result;
}
函数组合(输入,keyIndex=0,current={},result=[]){
常量键=对象键(输入)
常量键=键[键索引]
常量值=输入[键]
for(常量索引值){
当前[键]=值[索引]
if(键索引+1<键长度){
组合(输入、键索引+1、当前、结果)
}否则{
push(JSON.parse(JSON.stringify(当前)))
}
}
返回结果;
}
如果带有对象的数组再次调用
getCartesian
并构建新对象,则可以使用递归函数分离所有键/值对,并通过迭代值来构建新的笛卡尔积
这也适用于嵌套对象
函数getCartesian(对象){
返回Object.entries(Object).reduce((r[k,v])=>{
var-temp=[];
r、 forEach(s=>
(Array.isArray(v)?v:[v]).forEach(w=>
(w&&typeof w==='object'?getCartesian(w):[w])。forEach(x=>
临时推送(对象赋值({},s,{[k]:x}))
)
)
);
返回温度;
}, [{}]);
}
变量输入={a:[true,false],b:['first','second'],c:{d:[true,false]},
笛卡尔=getCartesian(输入);
console.log(笛卡尔)代码>
作为控制台包装{max height:100%!important;top:0;}
非常感谢,这正是我要搜索的!我喜欢你用entries/reduce方法做的事情。
const output = [
{
a: true,
b: 'first',
c: {
d: true
}
},
{
a: true,
b: 'first',
c: {
d: false
}
},
{
a: true,
b: 'second',
c: {
d: true
}
},
{
a: true,
b: 'second',
c: {
d: false
}
},
//...
]
function combinations(input, keyIndex = 0, current = {}, result = []) {
const keys = Object.keys(input)
const key = keys[keyIndex]
const values = input[key]
for (const index in values) {
current[key] = values[index]
if (keyIndex + 1 < keys.length) {
combinations(input, keyIndex + 1, current, result)
} else {
result.push(JSON.parse(JSON.stringify(current)))
}
}
return result;
}