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

时间:2019-04-13 13:33:36

标签: javascript arrays multidimensional-array

我说我有

foo

如何将其转换为

template <typename ... Args>
foo(Args...) -> foo<sizeof...(Args)>;

我的做法是:

f8

只是想知道还有没有更短的方法?

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

您可以构建笛卡尔积。

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

答案 2 :(得分:0)

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

let target = item.Key2.reduce((i, _) => {
  i.push([item.Key1, _]);
  return i;
}, []);

console.log(target)