假设我有
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)
关于javascript - 对象值的笛卡尔积(到数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55666049/