es6:隐藏对象到数组

时间:2018-03-06 06:28:49

标签: javascript ecmascript-6

我有记录:

 let a =  [{
            "resource" : "user",

            "permissions" : [ 
                "add", 
                "list", 
                "verify", 
                "add-credit", 
                "deactive", 
                "trash", 
                "edit", 
                "impersonate", 
                "active"
            ]
        }, 
        {
            "resource" : "company",

            "permissions" : [ 
                "list", 
                "verify", 
                "pending", 
                "reject"
            ]
        }];

我想将其转换为:

{"user":[ 
                "add", 
                "list", 
                "verify", 
                "add-credit", 
                "deactive", 
                "trash", 
                "edit", 
                "impersonate", 
                "active"
         ], 
        "company" : [ 
                "list", 
                "verify", 
                "pending", 
                "reject"
            ]
     };

这可以通过自定义函数来完成,并将结果存储到另一个变量。

我想要的是使用mapfilter或es6中任何新的javascript功能。

我尝试过使用map

 a.map(function (res){return res.resource})

2 个答案:

答案 0 :(得分:6)

使用reduce

var output = a.reduce( ( acc, c ) => {
  acc[ c.resource ] = c.permissions;
  return acc; //return accumulator
} ,{}) // initialize accumulator to {}

<强>解释

  • 使用reduce 迭代并初始化累加器 acc 空对象 {}
  • 对于数组c中的每个项a
    • c.resource值(用户公司)作为属性分配给acc(累加器),该属性的值为{{1} }
    • c.permissions 累加器 return

答案 1 :(得分:0)

尽管使用reduce已经回答了这个问题,但这只是为了澄清它可以通过这种方式完成,如果你不理解reduce如何工作或者你不理解想要使用reduce

&#13;
&#13;
let a =  [{
            "resource" : "user",

            "permissions" : [ 
                "add", 
                "list", 
                "verify", 
                "add-credit", 
                "deactive", 
                "trash", 
                "edit", 
                "impersonate", 
                "active"
            ]
        }, 
        {
            "resource" : "company",

            "permissions" : [ 
                "list", 
                "verify", 
                "pending", 
                "reject"
            ]
        }];
        
var res = {};
a.forEach((obj)=>{
  res[obj.resource] = obj.permissions;
});
console.log(res);
&#13;
&#13;
&#13;