我使用 Angularjs。 我有下一个数据,例如:
let filters = {
'async':[3,7],
'gpu_freq':[400,500]
};
有没有比很多循环更好的方法来获得以下组合?
[{
'async': 3,
'gpu_freq': 400
},{
'async': 3,
'gpu_freq': 50
},{
'async': 7,
'gpu_freq': 400
},{
'async': 7,
'gpu_freq': 500
}]
过滤器数量可以不同
最佳答案
如果包含对象的数组再次调用 getCartesian
并构建新对象,您可以通过迭代值来获得笛卡尔积。
这也适用于嵌套对象。
function getCartesian(object) {
return 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 =>
temp.push(Object.assign({}, s, { [k]: x }))
)
)
);
return temp;
}, [{}]);
}
var filters = { async: [3, 7], gpu_freq: [400, 500] },
cartesian = getCartesian(filters);
console.log(cartesian);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - JS : Dict of arrays combining by AND operation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52872713/