如何将键值元组的数组转换为对象

我有一个数组:

[ [ '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。如何将上面的元组数组转换为对象,以便按键轻松访问数据。

125390 次浏览

使用以下方法轻松地将数组转换为对象。

var obj = {};
array.forEach(function(e){
obj[e[0]] = e[1]
})

这将使用第一个元素作为键,第二个元素作为每个元素的值。

2020年6月最新情况

ECMAScript 2021带来了完全符合以下要求的 Object.fromEntries:

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

这样就行了:

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);


最简单的方法是使用 JSON 数据的 array:

var obj = {};
array.forEach(function(Data){
obj[Data[0]] = Data[1]
})

一种更为惯用的方法是使用 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>'))

如果使用 ES6(剩余参数)语法,这在视觉上更具吸引力:

let obj = arr.reduce((o, [ key, value ]) => {
o[key] = value
return o
}, {})

使用 地图

new Map(array);

Map 对象保存键-值对并记住原始 键的插入顺序。任何值(包括对象和基元) 值)可以用作键或值。

这是因为变量 array的类型是 Array<[key,value]>Map构造函数可以用一个数组数组初始化,其中内部数组的第一个元素是键,第二个元素是值。

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 = new Map(array);


console.log(obj.get('txnDate'));

作为 包的笔记,自2019年以来,你可以使用 Object.fromEntries(arr)(医生)在所有现代浏览器上做到这一点:

var arr = [['cardType', 'iDEBIT'],
['txnAmount', '17.64'],
['txnId', '20181']];


console.log(Object.fromEntries(arr));

如果这不可用,我以前的解决方案是映射到键值对象的数组,并通过 扩散将这些对象组合成 对象. 分配:

Object.assign(...arr.map(([key, val]) => ({[key]: val})))

我更推荐您使用 ES6与它的完美 Object.assign()方法。

Object.assign({}, ...array.map(([ key, value ]) => ({ [key]: value })));

这里发生了什么-Object.assign()什么也不做,只是从捐赠对象中获取键: 值,并将成对放入结果中。在本例中,我使用 ...将新的 array拆分为多个对(映射后看起来像 [{'cardType':'iDEBIT'}, ... ])。因此,最后,新的 {}从映射的 array的每个对中接收每个 key: property。

arr.reduce((o, [key, value]) => ({...o, [key]: value}), {})

您可以在 ES6中使用 array reduce 轻松实现这一点

在这个示例中,我们创建一个 reduce 函数,并将一个对象“{}”作为初始值传递给 reduce 函数和 reduce 函数

const 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' ] ];


const reducer = (obj, item) => {
obj[item[0]] = item[1];
return obj;
};


const result = arr.reduce(reducer, {});


console.log(result);

简短的 ES6方式与 Airbnb 代码风格

例如:

const obj = arr.reduce((prevObj, [key, value]) => ({ ...prevObj, [key]: value }), {});

ES5版本使用 .reduce()

const object = array.reduce(function(accumulatingObject, [key, value]) {
accumulatingObject[key] = value;
return accumulatingObject;
}, {});

这方面的新 JS API 是 Object.fromEntries(array of tuples),它可以处理原始数组和/或地图

使用 Object.fromEntries,你可以从 Array转换到 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);

let obj ={'abc':123,'other':566};


// first way
let coll= Object.entries(obj).map(i=>Object.assign({'key':i[0],'value':i[1]}))


results: coll =>
0: {key: "abc", value: 123}
1: {key: "other", value: 566}


// second way
let coll2= new Map(Object.entries(obj))
results: coll2 =?
//[[Entries]]
0: {"abc" => 123}
1: {"other" => 566}