Which is the easiest way to convert this:
[{src:\"websrv1\"}, {dst:\"websrv2\"}, {dstport:\"80\"}]
to this:
{src:\"websrv1\
Use .reduce()
.
var result = data.reduce(function(obj, item) {
for (var key in item)
obj[key] = item[key];
return obj;
}, {});
My 2cents, very easy to read:
var myObj = {};
myArray.forEach(function(obj) {
var prop = Object.keys(obj)[0];
myObj[prop] = obj[prop];
})
If you are using jquery, try this:
var array = [{src:"websrv1"}, {dst:"websrv2"}, {dstport:"80"}]
var arrayObj = {};
for(var i in array) {
$.extend(arrayObj, array[i]);
}
Don't use this! but just for fun
var a = [{src:"websrv1"}, {dst:"websrv2"}, {dstport:"80"}];
var f = a.reduce((c,d) => Object.assign(c,d), {})
The tiny drawback is that a
is mutated with an infinite recursive object but, who cares? it works in one line!
Here's a simple solution:
var output = {};
for (var i = 0; i < input.length; i++)
{
for (var n in input[i])
{
output[n] = input[i][n];
}
}
Demonstration
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