如何将键值元组数组转换为对象 [英] How to convert an array of key-value tuples into an object
本文介绍了如何将键值元组数组转换为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组:
[ [ '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);
这篇关于如何将键值元组数组转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文