Skip to content

Javascript: Convert Array to Object

Which is the easiest way to convert this:

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

to this:

{src:"websrv1", dst:"websrv2", dstport:"80"}

in order to pass it to AJAX data?

I’m using VisualSearch and it returns an array of Facet model instances which i need to convert into an Object.

Answer

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