我想说
const item = {
"Key1": "Value1",
"Key2": ["Value2", "Value3"]
}
如何将其格式化为
[["Value1","Value2"],["Value1","Value3"]]
?
我的做法是:
let array = [];
for (let i of item.Key2){
array.push([item.Key1,i])
}
只是想知道有没有更短的方法?
// 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)
你可以建立一个笛卡尔积。
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)