[英]Cartesian product of object values (to array)
Let say I have 假设我有
const item = {
"Key1": "Value1",
"Key2": ["Value2", "Value3"]
}
How can I turn it into format as 如何将其转换为
[["Value1","Value2"],["Value1","Value3"]]
? ?
My way of doing is: 我的做法是:
let array = [];
for (let i of item.Key2){
array.push([item.Key1,i])
}
Just wondering is there any shorter method? 只是想知道还有没有更短的方法?
// What question mentions const item = { "Key1": "Value1", "Key2": ["Value2", "Value3"] } let res = item.Key2.map(i => [item.Key1, i]) console.log(res)
// What the world wants! const item = { "Key1": ["ValueA", "ValueB"], "Key2": ["Value1", "Value2"] } res = item.Key1.reduce((acc, i1) => acc.concat(item.Key2.map(i2 => [i1, i2])), []) console.log(res)
You could build a cartesian product. 您可以构建笛卡尔积。
const item = { Key1: "Value1", Key2: ["Value2", "Value3"] }, values = Object.values(item).map(v => [].concat(v)), result = values.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), [])); console.log(result);
const item = { Key1: "Value1", Key2: ["Value2", "Value3"]}; let target = item.Key2.reduce((i, _) => { i.push([item.Key1, _]); return i; }, []); console.log(target)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.