Let say I have

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

How can I turn it into format as

[["Value1","Value2"],["Value1","Value3"]] 

?

My way of doing is:

let array = [];
for (let i of item.Key2){
  array.push([item.Key1,i])
}

Just wondering is there any shorter method?

3 Answers

2
Yan Foto On Best Solutions

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

2
Nina Scholz On

You could build a cartesian product.

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

0
user10988043 On

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

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

console.log(target)