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

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

I have an array:

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


        
相关标签:
15条回答
  • 2020-12-07 20:50

    easiest way to do it where array is of your JSON data :

    var obj = {};
    array.forEach(function(Data){
    obj[Data[0]] = Data[1]
    })
    
    0 讨论(0)
  • 2020-12-07 20:50

    In my case, all other solutions didn't work, but this one did:

    obj = {...arr}
    

    my arr is in a form: [name: "the name", email: "the@email.com"]

    0 讨论(0)
  • 2020-12-07 20:53

    ES5 Version using .reduce()

    const object = array.reduce(function(accumulatingObject, [key, value]) {
      accumulatingObject[key] = value;
      return accumulatingObject;
    }, {});
    
    0 讨论(0)
提交回复
热议问题