sdkks sdkks - 29 days ago 7
Node.js Question

Javascript/Node.js: Convert array with sub-arrays into object

I have an array that looks like this

var myArray = [
['a', 1],
['b', 2],
['c', 3]
]


I want to convert it into an object, it should be equal to below:

var myObj = {
'a' : 1,
'b' : 2,
'c' : 3
}


What is the easier and safer (if unexpected input comes) way to go about it?

Update:
To elaborate more on 'safer', sometimes I might get different input like

var myArray = [
['a', 1],
['b', 2],
['c', 3, 4, 5]
]


or

var myArray = [
['a', 1],
['b', 2],
['c', 3],
['d']
]


Regardless myObj should be equal to:

var myObj = {
'first-key' : 'firts-value'
}


or if 2nd element is not available in sub-array

var myObj = {
'first-key' : ''
}

Answer

You can do this with reduce()

var myArray = [
  ['a', 1],
  ['b', 2],
  ['c', 3]
]

var result = myArray.reduce((r, e) => {
  r[e[0]] = e[1];
  return r;
} , {});

console.log(result)

Comments