[javascript] How to convert an array of key-value tuples into an object

I have an array:

[ [ 'cardType', 'iDEBIT' ],
  [ 'txnAmount', '17.64' ],
  [ 'txnId', '20181' ],
  [ 'txnType', 'Purchase' ],
  [ 'txnDate', '2015/08/13 21:50:04' ],
  [ 'respCode', '0' ],
  [ 'isoCode', '0' ],
  [ 'authCode', '' ],
  [ 'acquirerInvoice', '0' ],
  [ 'message', '' ],
  [ 'isComplete', 'true' ],
  [ 'isTimeout', 'false' ] ]

But I can't access data via an array's key, e.g. arr['txnId'] does not return 20181. How can I convert the above array of tuples into an object, so that I can easily access data by key.

This question is related to javascript arrays

The answer is


Update 2020: As baao notes, Object.fromEntries(arr) now does this on all modern browsers.


You can use Object.assign, the spread operator, and destructuring assignment for an approach that uses map instead of @royhowie’s reduce, which may or may not be more intuitive:

Object.assign(...arr.map(([key, val]) => ({[key]: val})))

E.g.:

_x000D_
_x000D_
var arr = [ [ 'cardType', 'iDEBIT' ],
  [ 'txnAmount', '17.64' ],
  [ 'txnId', '20181' ],
  [ 'txnType', 'Purchase' ],
  [ 'txnDate', '2015/08/13 21:50:04' ],
  [ 'respCode', '0' ],
  [ 'isoCode', '0' ],
  [ 'authCode', '' ],
  [ 'acquirerInvoice', '0' ],
  [ 'message', '' ],
  [ 'isComplete', 'true' ],
  [ 'isTimeout', 'false' ] ]

var obj = Object.assign(...arr.map(([key, val]) => ({[key]: val})))

console.log(obj)
_x000D_
_x000D_
_x000D_


ES5 Version using .reduce()

const object = array.reduce(function(accumulatingObject, [key, value]) {
  accumulatingObject[key] = value;
  return accumulatingObject;
}, {});

With Object.fromEntries, you can convert from Array to Object:

_x000D_
_x000D_
var entries = [_x000D_
  ['cardType', 'iDEBIT'],_x000D_
  ['txnAmount', '17.64'],_x000D_
  ['txnId', '20181'],_x000D_
  ['txnType', 'Purchase'],_x000D_
  ['txnDate', '2015/08/13 21:50:04'],_x000D_
  ['respCode', '0'],_x000D_
  ['isoCode', '0'],_x000D_
  ['authCode', ''],_x000D_
  ['acquirerInvoice', '0'],_x000D_
  ['message', ''],_x000D_
  ['isComplete', 'true'],_x000D_
  ['isTimeout', 'false']_x000D_
];_x000D_
var obj = Object.fromEntries(entries);_x000D_
console.log(obj);
_x000D_
_x000D_
_x000D_


use the following way to convert the array to an object easily.

var obj = {};
array.forEach(function(e){
   obj[e[0]] = e[1]
})

This will use the first element as the key and the second element as the value for each element.


arr.reduce((o, [key, value]) => ({...o, [key]: value}), {})

easiest way to do it where array is of your JSON data :

var obj = {};
array.forEach(function(Data){
obj[Data[0]] = Data[1]
})

When I used the reduce function with acc[i] = cur; it returned a kind of object that I needed to access it like a array using this way obj[i].property. But using this way I have the Object that I wanted and I now can access it like obj.property.

 function convertArraytoObject(arr) {
        var obj = arr.reduce(function (acc, cur, i) {
            acc = cur;
            return acc;
        }, {});
        return obj;
    }

In my case, all other solutions didn't work, but this one did:

obj = {...arr}

my arr is in a form: [name: "the name", email: "[email protected]"]


Short ES6 way with Airbnb code style

Exemple:

const obj = arr.reduce((prevObj, [key, value]) => ({ ...prevObj, [key]: value }), {});

You could do this easily using array reduce in ES6

In this example we create a reducer function and pass an object '{}' as initial value to the reduce function along with the reducer

_x000D_
_x000D_
const arr =    [ [ 'cardType', 'iDEBIT' ],_x000D_
  [ 'txnAmount', '17.64' ],_x000D_
  [ 'txnId', '20181' ],_x000D_
  [ 'txnType', 'Purchase' ],_x000D_
  [ 'txnDate', '2015/08/13 21:50:04' ],_x000D_
  [ 'respCode', '0' ],_x000D_
  [ 'isoCode', '0' ],_x000D_
  [ 'authCode', '' ],_x000D_
  [ 'acquirerInvoice', '0' ],_x000D_
  [ 'message', '' ],_x000D_
  [ 'isComplete', 'true' ],_x000D_
  [ 'isTimeout', 'false' ] ];_x000D_
_x000D_
const reducer = (obj, item) => {_x000D_
  obj[item[0]] = item[1];_x000D_
  return obj;_x000D_
};_x000D_
_x000D_
const result = arr.reduce(reducer, {});_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_


I much more recommend you to use ES6 with it's perfect Object.assign() method.

Object.assign({}, ...array.map(([ key, value ]) => ({ [key]: value })));

What happening here - Object.assign() do nothing but take key:value from donating object and puts pair in your result. In this case I'm using ... to split new array to multiply pairs (after map it looks like [{'cardType':'iDEBIT'}, ... ]). So in the end, new {} receives every key:property from each pair from mapped array.


Use Map.

new Map(array);

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

This works because the type of your variable array is Array<[key,value]>. The Map constructor can be initialized with an array of arrays where the first element of the inner arrays is the key and the second is the value.

_x000D_
_x000D_
const array = [_x000D_
  ['cardType', 'iDEBIT'],_x000D_
  ['txnAmount', '17.64'],_x000D_
  ['txnId', '20181'],_x000D_
  ['txnType', 'Purchase'],_x000D_
  ['txnDate', '2015/08/13 21:50:04'],_x000D_
  ['respCode', '0'],_x000D_
  ['isoCode', '0'],_x000D_
  ['authCode', ''],_x000D_
  ['acquirerInvoice', '0'],_x000D_
  ['message', ''],_x000D_
  ['isComplete', 'true'],_x000D_
  ['isTimeout', 'false']_x000D_
];_x000D_
_x000D_
const obj = new Map(array);_x000D_
_x000D_
console.log(obj.get('txnDate'));
_x000D_
_x000D_
_x000D_


The new JS API for this is Object.fromEntries(array of tuples), it works with raw arrays and/or Maps


A more idiomatic approach would be to use Array.prototype.reduce:

_x000D_
_x000D_
var arr = [_x000D_
  [ 'cardType', 'iDEBIT' ],_x000D_
  [ 'txnAmount', '17.64' ],_x000D_
  [ 'txnId', '20181' ],_x000D_
  [ 'txnType', 'Purchase' ],_x000D_
  [ 'txnDate', '2015/08/13 21:50:04' ],_x000D_
  [ 'respCode', '0' ],_x000D_
  [ 'isoCode', '0' ],_x000D_
  [ 'authCode', '' ],_x000D_
  [ 'acquirerInvoice', '0' ],_x000D_
  [ 'message', '' ],_x000D_
  [ 'isComplete', 'true' ],_x000D_
  [ 'isTimeout', 'false' ]_x000D_
];_x000D_
_x000D_
var obj = arr.reduce(function (o, currentArray) {_x000D_
  var key = currentArray[0], value = currentArray[1]_x000D_
  o[key] = value_x000D_
  return o_x000D_
}, {})_x000D_
_x000D_
console.log(obj)_x000D_
document.write(JSON.stringify(obj).split(',').join(',<br>'))
_x000D_
_x000D_
_x000D_

This is more visually appealing, when done with ES6 (rest parameters) syntax:

let obj = arr.reduce((o, [ key, value ]) => {
    o[key] = value
    return o
}, {})