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

时间:2018-11-07 07:20:43

标签: javascript ecmascript-6

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语句来实现,但这确实很。脚。还有其他方法可以实现吗?

4 个答案:

答案 0 :(得分:4)

您可以将另一个对象用作措词,然后通过在与逗号连接之前用“&”和所有单词替换最后两个单词来创建一个漂亮的字符串。

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

答案 1 :(得分:3)

您可以这样做:

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

答案 2 :(得分:1)

这是我的尝试。在学习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))

答案 3 :(得分:0)

这应该可以完成工作:

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",您仍然可以对其进行修改。