为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

手掌心 2021-04-09 14:15:28
假设我有const item = {  "Key1": "Value1",  "Key2": ["Value2", "Value3"]}如何将其转换为[["Value1","Value2"],["Value1","Value3"]] ?我的做法是:let array = [];for (let i of item.Key2){  array.push([item.Key1,i])}只是想知道还有没有更短的方法?
查看完整描述

3 回答

?
红颜莎娜

TA贡献1842条经验 获得超12个赞

// 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)


查看完整回答
反对 回复 2021-04-29
?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

您可以构建笛卡尔积。


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);


查看完整回答
反对 回复 2021-04-29
?
慕慕森

TA贡献1856条经验 获得超17个赞

const item = { Key1: "Value1", Key2: ["Value2", "Value3"]};


let target = item.Key2.reduce((i, _) => {

  i.push([item.Key1, _]);

  return i;

}, []);


console.log(target)


查看完整回答
反对 回复 2021-04-29
  • 3 回答
  • 0 关注
  • 178 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信