Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

maping correct structure text

How do I make this structure:

busy: admin1,admin2,admin3,
sleep: admin0,

I don’t know what I’m doing wrong, I need to line it all up

const user = [
  {
  status: "busy", 
  username: "admin1"},
 {
  status: "busy", 
  username: "admin2"},
  {
  status: "busy", 
  username: "admin3"},
{
  status: "sleep", 
  username: "admin0"},
]

let text = ``
user.map((v) => {
text += `${v.status}: ${v.username}\n`
})

console.log(text)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

busy: admin1
busy: admin2
busy: admin3
sleep: admin0

I need to do it correctly, how?
I don’t know what I should do next I’m up

>Solution :

You could group them first (use array.reduce) and then create the texts from there.

const user = [{
    status: "busy",
    username: "admin1"
  },
  {
    status: "busy",
    username: "admin2"
  },
  {
    status: "busy",
    username: "admin3"
  },
  {
    status: "sleep",
    username: "admin0"
  },
]

const grouped = user.reduce((groups, user) => ({
  ...groups,
  [user.status]: [...(groups[user.status] || []), user.username]
}), {});

const text = Object.entries(grouped).map(([key, values]) => `${key}: ${values}`).join('\n');

console.log(text);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading