[removed] Convert Array to Object

后端 未结 6 1228
执念已碎
执念已碎 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:32

    Use .reduce().

    var result = data.reduce(function(obj, item) {
        for (var key in item)
            obj[key] = item[key];
        return obj;
    }, {});
    
    0 讨论(0)
  • 2021-01-16 03:32

    My 2cents, very easy to read:

    var myObj = {};
    myArray.forEach(function(obj) {
      var prop = Object.keys(obj)[0];
      myObj[prop] = obj[prop];
    })
    
    0 讨论(0)
  • 2021-01-16 03:37

    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]);
    }
    
    0 讨论(0)
  • 2021-01-16 03:51

    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!

    0 讨论(0)
  • 2021-01-16 03:53

    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

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题