Convert array of object to single object in javascript(Angularjs)

后端 未结 3 1707
孤城傲影
孤城傲影 2021-01-24 05:46

How to do convert array of objects like this:

[
   { 
      display_name: \"view_dashboard\",
      value: 1
   },
   { 
      display_name: \"view_user\",
              


        
相关标签:
3条回答
  • 2021-01-24 05:51

    You could try using the reduce function:

    var myArray =[
       { 
          display_name: "view_dashboard",
          value: 1
       },
       { 
          display_name: "view_user",
          value: 0
       }
    ]
    
    var result = myArray.reduce(function(obj, item) {
        obj[item.display_name] = item.value;
        return obj;
    }, {})
    
    console.log(result); // {view_dashboard: 1, view_user: 0}
    
    0 讨论(0)
  • 2021-01-24 05:59

    An approach with a Array#forEach:

    var array = [{ display_name: "view_dashboard", value: 1 }, { display_name: "view_user", value: 0 }],
        object = {};
    
    array.forEach(function (o) {
        object[o.display_name] = o.value;
    });
    
    document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');

    0 讨论(0)
  • 2021-01-24 06:10

    You can try Array.map

    var data = [{
      display_name: "view_dashboard",
      value: 1
    }, {
      display_name: "view_user",
      value: 0
    }];
    
    var result = data.map(function(o){
      var _tmp = {};
      _tmp[o.display_name] = o.value
      return _tmp;
    });
    
    document.write("<pre>" + JSON.stringify(result,0,4) + "</pre>");

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