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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32002176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:29:49  来源:igfitidea点击:

How to convert an array of key-value tuples into an object

javascriptarrays

提问by Anthony

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.

但是我无法通过数组的键访问数据,例如arr['txnId']不返回20181。如何将上述元组数组转换为对象,以便我可以轻松地通过键访问数据。

采纳答案by baao

This will do it:

这将做到:

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

回答by Toph

You can use Object.assign, the spread operator, and destructuring assignmentfor an approach that uses mapinstead of @royhowie's reduce, which may or may not be more intuitive:

您可以使用Object.assign展开运算符解构赋值map代替@royhowie's 的方法reduce,这可能更直观,也可能不更直观:

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

E.g.:

例如:

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 = Object.assign(...arr.map(([key, val]) => ({[key]: val})))

console.log(obj)

回答by royhowie

A more idiomatic approach would be to use Array.prototype.reduce:

更惯用的方法是使用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:

当使用 ES6(其余参数)语法完成时,这在视觉上更具吸引力:

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

回答by Rick Viscomi

Use Map.

使用地图

new Map(array);

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

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

This works because the type of your variable arrayis Array<[key,value]>. The Mapconstructor can be initialized with an array of arrays where the first element of the inner arrays is the key and the second is the value.

这是有效的,因为您的变量类型arrayArray<[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'));

回答by Oswaldo

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

回答by Penny Liu

With Object.fromEntries, you can convert from Arrayto Object:

使用Object.fromEntries,您可以从 转换ArrayObject

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

回答by sudo soul

ES5 Version using .reduce()

ES5 版本使用 .reduce()

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

回答by Imesh Chandrasiri

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.

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

回答by Vaibhav Namburi

The new JS API for this is Object.fromEntries(array of tuples), it works with raw arrays and/or Maps

新的 JS API 是Object.fromEntries(array of tuples),它适用于原始数组和/或地图

回答by A. Moynet

Short ES6 way with Airbnb code style

Airbnb 代码风格的简短 ES6 方式

Exemple:

例子:

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