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.
As baao notes, since 2019 you can use Object.fromEntries(arr)
(docs) to do exactly this on all modern browsers:
var arr = [['cardType', 'iDEBIT'], ['txnAmount', '17.64'], ['txnId', '20181']]; console.log(Object.fromEntries(arr));
If that’s not available, my previous solution was to map to an array of key-value objects and combine the objects by spreading into Object.assign:
Object.assign(...arr.map(([key, val]) => ({[key]: val})))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With