how to merge array to a multi array as key value pair

Asked 1 month ago
Viewed 13 times

 var r = {},
 i,
    keys = ['one', 'two', 'three'],
    values = ['a', 'b', 'c'],['d', 'e',' f'];

for (let i = 0; i < keys.length; i++) {
    r[keys[i]] = values[i];
}

console.log(r);

Im just getting this error from my console. Uncaught SyntaxError: Invalid destructuring assignment target

This is the output i want to get.

{
  "one": "a",
  "two": "b",
  "three": "c"
},
{
  "one": "d",
  "two": "e",
  "three": "f"
}

asked 1 month ago

Correct Answer

The main destructuring error occurs because you have an invalid values assignment, I added some square brackets around the two arrays to fix that.

let keys = ['one', 'two', 'three'],
 values = [['a', 'b', 'c'],['d', 'e',' f']];
    
let r = values.map(v => 
  Object.fromEntries(
    keys.map((k, i) => ([k, v[i]]))
  )
);

console.log(r);
answered 1 month ago