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

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

I have an array:

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


        
15条回答
  •  暖寄归人
    2020-12-07 20:38

    Update June 2020

    ECMAScript 2021 brings Object.fromEntries which does exactly the requirement:

    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

    This will do it:

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


提交回复
热议问题