如何在JS中基于布尔值自动在单词之间插入逗号或符号


const confirmations = {
quantity: false,
total_price: true,
unit_price: true
}
// Should print -> Total Price & Unit Price
// If three variables are true then should print -> Quantity, Total Price & Unit Price

我知道这可以通过使用几个if...else语句来实现,但这真的很蹩脚。还有其他方法可以做到这一点吗?

您可以使用另一个对象作为措辞,然后通过将最后两个单词替换为"与"符号,并将联接之前的所有单词替换为逗号来创建一个漂亮的字符串。

function getString(confirmations) {
const
nice = a => a.concat(a.splice(-2, 2).join(' & ')).join(', '),
words = { quantity: 'Quantity', total_price: 'Total Price', unit_price: 'Unit Price' };
return nice(Object
.entries(confirmations)
.filter(([, v]) => v)
.map(([w]) => words[w])
);
}
console.log(getString({ quantity: false, total_price: true, unit_price: true }));
console.log(getString({ quantity: true, total_price: true, unit_price: true }));
console.log(getString({ quantity: false, total_price: true, unit_price: false }));

你可以做:

const confirmations1 = {quantity: false, total_price: true, unit_price: true};
const confirmations2 = {quantity: true, total_price: true, unit_price: true};
const getFormattedSentence = obj => Object
.keys(obj)
.filter(k => obj[k])
.map(k => k
.split('_')
.map(w => w.charAt(0).toUpperCase() + w.slice(1))
.join(' ')
)
.join(', ')
.replace(/,(?!.*,)/gmi, ' &');

console.log(getFormattedSentence(confirmations1));
console.log(getFormattedSentence(confirmations2));

这是我的尝试。在研究了Yosvel Quintero的版本后,身材更加苗条

const fmtText = obj => Object
.keys(obj)                     // array of keys
.filter(k => obj[k])           // take only the true ones 
.join(", ")                    // join found keys with ,
.replace(/_/g, " ")            // replace the underscore
.replace(/b([a-z])/g, x => x.toUpperCase()) // InitialCap
.replace(/,(?=[^,]*$)/, ' &'); // replace last comma
const conf1 = { quantity: false, total_price: true, unit_price: true }
const conf2 = { quantity: true,  total_price: true, unit_price: true }
const conf3 = { quantity: false, total_price: true, unit_price: false }
console.log(fmtText(conf1))
console.log(fmtText(conf2))
console.log(fmtText(conf3))

这应该完成任务:

const confirmations = {
quantity: false,
total_price: true,
unit_price: true
};
// filter out false values and return object keys as an array of strings
const validatedConfirmations = Object.keys(confirmations).filter((name) => confirmations[name]);
// make them human readable
const humanReadableConfirmations = validatedConfirmations.map(makeItHumanReadable);
// crunch it all to a single string
const lastConfirmationMessage = humanReadableConfirmations.pop();
const confirmationMessage = humanReadableConfirmation.join(', ') + ` & ${lastConfirmationMessage}`;

小心,如果只有一个元素为真,它将显示"& Unit Price",您无论如何都可以调整它。

最新更新