简体   繁体   中英

How to space strings in an array of strings

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 🟢

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM