如何将键值元组数组转换为对象
问题描述:
我有一个数组:
[ [ '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' ] ]
但是我无法通过数组的密钥访问数据,例如 arr ['txnId']
未返回 20181
。如何将上面的元组数组转换为对象,以便我可以通过键轻松访问数据。
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.
答
这将这样做:
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);