0

I am trying to create a dynamic list using the following code:

const permissions: string[] = []

Object.keys(userPerms).forEach((key) => {
  permissions.push(`${capitalise(key)} ${userPerms[key] ? '🟢' : '🔴'}`)
})

The output I want:

Send Messages   🟢
Join Call       🔴
Send Emojis     🟢

The output I am getting with my current code:

Send Messages 🟢
Join Call 🔴
Send Emojis 🟢
5
  • What about the code you've written leads you to expect that output? Commented Jun 3, 2020 at 2:50
  • 3
    Where is the result displayed? The basic idea would be to work out the longest key and use String.prototype.padEnd() to make up the difference for shorter strings. If you're displaying this in HTML though, you can probably just use CSS Commented Jun 3, 2020 at 2:53
  • Are you trying to align the output during the list insertion using string concatenation? Commented Jun 3, 2020 at 2:54
  • I have edited my question to make what I am asking for clearer. Commented Jun 3, 2020 at 2:56
  • @Phil I am outputting this on a Discord message embed, how would I work out the longest key? Commented Jun 3, 2020 at 2:58

1 Answer 1

1

You can use this snippet. You need to calculate the maximum length of the permission string key. After that add spaces according to that maximum length. If you want to do it by hand.

let userPerms = {
  "Send Messages": true,
  "Join Call": false,
  "Send Emojis": true,
};

// Find maximum lenght
let max = 0;
Object.keys(userPerms).forEach((key) => {
  if (key.length > max) {
    max = key.length;
  }
});

// Give additional 2 spaces
max += 2;

const permissions = []
Object.keys(userPerms).forEach((key) => {
  permissions.push(key.concat(' '.repeat(max - key.length)) + (userPerms[key] ? '🟢' : '🔴'))
})

console.log(permissions);

More elegant solution will be:

let userPerms = {
  "Send Messages": true,
  "Join Call": false,
  "Send Emojis": true,
};
const permissions = []

// Find maximum lenght
let max = Object.keys(userPerms).sort(function (a, b) { return b.length - a.length; })[0].length + 2 // space between;
// Add to array
Object.keys(userPerms).forEach((key) => {
  permissions.push(key.padEnd(max) + (userPerms[key] ? '🟢' : '🔴'))
});

console.log(permissions);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.