I have an array:
[ [ \'cardType\', \'iDEBIT\' ],
[ \'txnAmount\', \'17.64\' ],
[ \'txnId\', \'20181\' ],
[ \'txnType\', \'Purchase\' ],
[ \'txnDate\
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.
With Object.fromEntries, you can convert from Array
to Object
:
var entries = [
['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.fromEntries(entries);
console.log(obj);
Short ES6 way with Airbnb code style
Exemple:
const obj = arr.reduce((prevObj, [key, value]) => ({ ...prevObj, [key]: value }), {});
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;
}
arr.reduce((o, [key, value]) => ({...o, [key]: value}), {})
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
}, {})