[removed] Convert Array to Object

后端 未结 6 1349
执念已碎
执念已碎 2021-01-16 03:19

Which is the easiest way to convert this:

[{src:\"websrv1\"}, {dst:\"websrv2\"}, {dstport:\"80\"}]

to this:

{src:\"websrv1\         


        
6条回答
  •  孤独总比滥情好
    2021-01-16 03:56

    var a = [{src:"websrv1"}, {dst:"websrv2"}, {dstport:"80"}];
    
     var b = a.reduce(
       function(reduced,next){
          Object.keys(next).forEach(function(key){reduced[key]=next[key];});
          return reduced;
       }
     );
    
    //b should be {src:"websrv1", dst:"websrv2", dstport:"80"}
    

    think about the array.reduce function everytime you need to perform these kind of transformations.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

提交回复
热议问题