[英]es6 : covert object to array
I have records : 我有记录:
let a = [{
"resource" : "user",
"permissions" : [
"add",
"list",
"verify",
"add-credit",
"deactive",
"trash",
"edit",
"impersonate",
"active"
]
},
{
"resource" : "company",
"permissions" : [
"list",
"verify",
"pending",
"reject"
]
}];
I want to convert it to : 我想将其转换为:
{"user":[
"add",
"list",
"verify",
"add-credit",
"deactive",
"trash",
"edit",
"impersonate",
"active"
],
"company" : [
"list",
"verify",
"pending",
"reject"
]
};
This can be done via the custom function to foreach and store the result to another variable. 这可以通过自定义函数进行foreach并将结果存储到另一个变量中来完成。
What I want is to do it with map
, filter
, or any new feature of javascript in es6. 我想要做的就是使用
map
, filter
或es6中javascript的任何新功能。
I have tried using map
. 我尝试使用
map
。
a.map(function (res){return res.resource})
Use reduce
使用
reduce
var output = a.reduce( ( acc, c ) => {
acc[ c.resource ] = c.permissions;
return acc; //return accumulator
} ,{}) // initialize accumulator to {}
Explanation 说明
reduce
to iterate and initialize the accumulator acc
as empty object {}
. reduce
迭代并将 累加器 acc
初始化为空对象 {}
。 c
in the array a
a
中的每一项c
c.resource
value ( user and company ) as property to acc
(accumulator) and value of that property being c.permissions
c.resource
值( 用户和公司 )作为属性分配给acc
(累加器),并且该属性的值是c.permissions
return
the accumulator acc
. return
累加器 acc
。 Although this has been answered by using reduce
but this is just to clarify that it can be done this way which is much more understanding if you do not understand how reduce
works or if you do not want to use reduce
尽管可以通过使用
reduce
来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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.