How to convert an array of key-value tuples into an object
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.:
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)
Update June 2020
ECMAScript 2021 brings Object.fromEntries
which does exactly the requirement:
const 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' ] ];
const obj = Object.fromEntries(array);
console.log(obj);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries
This will do it:
const 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' ] ];
var obj = {};
array.forEach(function(data){
obj[data[0]] = data[1]
});
console.log(obj);
A more idiomatic approach would be to use Array.prototype.reduce
:
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 = arr.reduce(function (o, currentArray) {
var key = currentArray[0], value = currentArray[1]
o[key] = value
return o
}, {})
console.log(obj)
document.write(JSON.stringify(obj).split(',').join(',<br>'))
This is more visually appealing, when done with ES6 (rest parameters) syntax:
let obj = arr.reduce((o, [ key, value ]) => {
o[key] = value
return o
}, {})