我有记录:
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"
]
};
这可以通过自定义函数来完成,并将结果存储到另一个变量。
我想要的是使用map
,filter
或es6中任何新的javascript功能。
我尝试过使用map
。
a.map(function (res){return res.resource})
答案 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
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;