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

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

I have an array:

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


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

    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.

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

    With Object.fromEntries, you can convert from Array to Object:

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

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

    Short ES6 way with Airbnb code style

    Exemple:

    const obj = arr.reduce((prevObj, [key, value]) => ({ ...prevObj, [key]: value }), {});
    
    0 讨论(0)
  • 2020-12-07 20:30

    When I used the reduce function with acc[i] = cur; it returned a kind of object that I needed to access it like a array using this way obj[i].property. But using this way I have the Object that I wanted and I now can access it like obj.property.

     function convertArraytoObject(arr) {
            var obj = arr.reduce(function (acc, cur, i) {
                acc = cur;
                return acc;
            }, {});
            return obj;
        }
    
    0 讨论(0)
  • 2020-12-07 20:31
    arr.reduce((o, [key, value]) => ({...o, [key]: value}), {})
    
    0 讨论(0)
  • 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(',<br>'))

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

    let obj = arr.reduce((o, [ key, value ]) => {
        o[key] = value
        return o
    }, {})
    
    0 讨论(0)
提交回复
热议问题