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

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

I have an array:

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


        
15条回答
  •  鱼传尺愫
    2020-12-07 20:39

    Update 2020: As baao notes, Object.fromEntries(arr) now does this on all modern browsers.


    You can use Object.assign, the spread operator, and destructuring assignment for an approach that uses map instead of @royhowie’s reduce, which may or may not be more intuitive:

    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)

提交回复
热议问题