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

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

I have an array:

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


        
15条回答
  •  孤城傲影
    2020-12-07 20:36

    I much more recommend you to use ES6 with it's perfect Object.assign() method.

    Object.assign({}, ...array.map(([ key, value ]) => ({ [key]: value })));
    

    What happening here - Object.assign() do nothing but take key:value from donating object and puts pair in your result. In this case I'm using ... to split new array to multiply pairs (after map it looks like [{'cardType':'iDEBIT'}, ... ]). So in the end, new {} receives every key:property from each pair from mapped array.

提交回复
热议问题