Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

javascript - Create new multidimensional array based on this existing array objec

I'm stuck to construct a new multidimensional array based on this existing array object

acl:[
{
   view:true, 
   update:true, 
   remove:true, 
   userId:1, 
   username:"Mike"
},
{
   view:true, 
   update:true, 
   remove:false, 
   userId:2, 
   username:"Joe"
},
{
   view:true, 
   update:false, 
   remove:false, 
   userId:3, 
   username:"Lim"
}
]

The new object will be constructed based on the boolean properties(if these boolean is equal to true). The new array will look like this

acl:[
{
view:[
   {username:"Mike", userId:1},
   {username:"Joe", userId:2},
   {username:"Lim", userId:3}
]
update:[
   {username:"Mike", userId:1},
   {username:"Joe", userId:2}
]
remove:[
   {username:"Mike", userId:1}
]

Im stuck on constructing the logic inside the iteration. Maybe someone could give me a hint on this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use reduce to group into an object of arrays:

const acl=[{view:!0,update:!0,remove:!0,userId:1,username:"Mike"},{view:!0,update:!0,remove:!1,userId:2,username:"Joe"},{view:!0,update:!1,remove:!1,userId:3,username:"Lim"}];

console.log(
  acl.reduce((a, { view, update, remove, userId, username }) => {
    const obj = { username, userId };
    if (view) a.view.push(obj);
    if (update) a.update.push(obj);
    if (remove) a.remove.push(obj);
    return a;
  }, { view: [], update: [], remove: [] })
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...