javascript - 对象值的笛卡尔积(到数组)

标签 javascript arrays multidimensional-array

假设我有

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/

相关文章:

javascript - 在 ng-repeat 之后执行 jQuery 函数

C strcpy 是否需要特定的缓冲区大小或仍然可以工作?

javascript - indexOf 但对于对象呢?

javascript - 如果没有鼠标点击事件,我如何对 onClick 进行单元测试?

javascript - 如何判断父节点是否是body节点?

php - 如何在 foreach 循环中选择 "sub-array"

php - 字符串到数组的转换、array_rand、取消设置以及返回数组到字符串。有捷径吗?

java - 将文件读入二维数组 - 获取 ArrayIndexOutOfBoundsException()

更改多维数组中的数据

c - 将 Objective C 中的多数组传递给函数