1

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' : ''
}
  • [like this](http://stackoverflow.com/questions/4215737/convert-array-to-object) – Kevin Kloet Nov 04 '16 at 15:22
  • @KevinKloet Elements in my array are arrays themselves. –  Nov 04 '16 at 15:24
  • 1
    Can you clarify what you mean by _unexpected input_? Strikes me as a very important requirement if it means you need to be able to handle things like `myArray` not being an array or somesuch. – tmslnz Nov 04 '16 at 15:27
  • @tmslnz Subarrays might have 1 element or sometimes more than 2. But I'm only interested in capturing first 2, if it has 1 element, value of key can be just `''` –  Nov 04 '16 at 15:28
  • @sdkks ok. And do those arrays need to be _flattened_ or `c: [1,2,3,4,5,…]` is an acceptable output? – tmslnz Nov 04 '16 at 15:29
  • @tmslnz I updated the question to make it clearer. Thanks –  Nov 04 '16 at 15:35
  • So what is result for `['c', 3, 4, 5]`? – Nenad Vracar Nov 04 '16 at 15:38
  • @NenadVracar your reduce solution works for both cases. I tested it just now. –  Nov 04 '16 at 15:40

4 Answers4

2

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)

Update: for cases where there is just one element in array (return '') or more then two (return array with rest of elements).

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

var result = myArray.reduce((r, e) => {
  r[e[0]] = (e[1]) ? ((e.length > 2) ? e.slice(1) : e[1]) : '';
  return r;
} , {});

console.log(result)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0
var myArray = [
    ['a', 1],
    ['b', 2],
    ['c', 3]
];

var myObj = {};

myArray.forEach(function(element){
    myObj[element[0]] = element[1];
})
Jeremy Jackson
  • 2,247
  • 15
  • 24
  • 1
    This code makes a lot of assumptions - and does not handle "unexpected input" as the OP asked. – mhodges Nov 04 '16 at 15:25
0

just use a forEach to populate myObj :

var myArray = [
    ['a', 1],
    ['b', 2],
    ['c', 3]
];
var myObj = {};
myArray.forEach(x => myObj[x[0]]=x[1]);
console.log(myObj);
kevin ternet
  • 4,514
  • 2
  • 19
  • 27
-1

None of the other answers handle unexpected input... The way to do this is with .reduce() and type checking.

var myArray = [
  [[1, 2, 3], 'a'], // [1] is valid property name, [0] valid value
  ['b', 2, 5, 2], // [0] is valid property name, [1] valid value
  ['c', undefined], // [0] is valid property name, [1] invalid value
  { prop1: "123" }, // Invalid - is not an array
  undefined, // Invalid - is not an array
  123, // Invalid - is not an array
  [undefined, 'd'], // [1] is valid property name, [0] valid value
  ['e'] // [0] is valid property name, [1] does not exist
];

function convertArrToObj(arr) {
  // check to ensure that parent is actually an array
  if (isArray(arr)) {
    return arr.reduce(function(obj, curr) {
      // check to ensure each child is an array with length > 0
      if (isArray(curr) && curr.length > 0) {
        // if array.length > 1, we are interested in [0] and [1]
        if (curr.length > 1) {
          // check if [0] is valid property name
          if (typeof curr[0] === "string" || typeof curr[0] === "number") {
            // if so, use [0] as key, and [1] as value
            obj[curr[0]] = curr[1] || ""
          } 
          // if not, check if [1] is a valid property name
          else if (typeof curr[1] === "string" || typeof curr[1] === "number") {
            // if so, use [1] as key, and [0] as value
            obj[curr[1]] = curr[0] || ""
          }
          // if no valid property names found, do nothing
        } else {
          // if array.length === 1, check if the one element is
          // a valid property name. 
          if (typeof curr[0] === "string" || typeof curr[0] === "number") {
            // If so, add it and use "" as value
            obj[curr[0]] = "";
          }
        }
      }
      // return updated object for next iteration
      return obj
    }, {});
  }
}

function isArray(val) {
  return val === Object(val) && Object.prototype.toString.call(val) === '[object Array]';
}

console.log(convertArrToObj(myArray));
mhodges
  • 10,938
  • 2
  • 28
  • 46