我已经找到了关于数组值之间所有可能组合的许多解决方案,但是我需要一些不同的东西,希望您能支持我。基本上是创建所有将数组键与true | false值组合的可能对象,如下所示:
输入:(应返回一个由32个对象组成的数组,2exp5、5个键中的两个可能值)
let properties = ['arm','lens','season','food','size'];
输出:
let combinations = [
{"arm": "false","lens": "false","season": "false","food": "false","size": "false"}
{"arm": "false","lens": "false","season": "false","food": "false","size": "true"}
{"arm": "false","lens": "false","season": "false","food": "true","size": "true"}
{"arm": "false","lens": "false","season": "true","food": "true","size": "true"}
{"arm": "false","lens": "true","season": "true","food": "true","size": "true"}
{"arm": "true","lens": "true","season": "true","food": "true","size": "true"}
{"arm": "true","lens": "true","season": "true","food": "false","size": "true"}
{"arm": "true","lens": "true","season": "false","food": "false","size": "true"}
and so on...
]
非常感谢!
您可以为每个属性使用带有打开和关闭开关的2D矩阵。然后为每个键创建条目,并使用Object.fromEntries()
0 0 0 0 0
0 0 0 0 1
0 0 0 1 0
0 0 0 1 1
etc
以下是代码段:
let keys = ['arm', 'lens', 'season', 'food', 'size'];
function combination(keys) {
return Array.from({ length: 2 ** keys.length }, (_, i) =>
Object.fromEntries(
i.toString(2)
.padStart(keys.length, 0)
.split('')
.map((binary, j) => [keys[j], String(Boolean(+binary))])
)
)
}
console.log(combination(keys))