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

后端 未结 15 1872
南方客
南方客 2020-12-07 20:11

I have an array:

[ [ \'cardType\', \'iDEBIT\' ],
  [ \'txnAmount\', \'17.64\' ],
  [ \'txnId\', \'20181\' ],
  [ \'txnType\', \'Purchase\' ],
  [ \'txnDate\         


        
15条回答
  •  感情败类
    2020-12-07 20:32

    A more idiomatic approach would be to use 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(',
    '))

    This is more visually appealing, when done with ES6 (rest parameters) syntax:

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

提交回复
热议问题