Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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: [] })
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...