首页 > 解决方案 > 如何在 Typescript Push 方法中编写 If Else

问题描述

我有一个推送方法,我正在推送一些键值对。我想写一个if-else condition。我想categories使用 If-else 条件设置(在'key':row [0],'value':row [1]之后)的值,而不是将其硬编码为通用设置。可能吗。如果是,那怎么办?

Object.entries(this.generalInfoForm.value).forEach((row, index) => {
console.log(this.finalObject.properties);
  // index < 5 ? this.finalObject.properties.push({ 'key': row[0], 'value': row[1], 'categories': objMap[row[0]] }) : '';
  index < 5 ? this.finalObject.properties.push({
    'key': row[0], 'value': row[1], 'categories': 'general-settings'
  }) : '';
});

标签: javascript

解决方案


不要想太多。只需categories提前确定值并使用它:

Object.entries(this.generalInfoForm.value).forEach((row, index) => {
    console.log(this.finalObject.properties);

    if (index < 5) {
        const categories =
            condition
                ? trueValue
                : falseValue;

        this.finalObject.properties.push({
            'key': row[0],
            'value': row[1],
            categories,
        });
    }
});

如果您真的想将它组合到对象创建表达式中,当然可以,但我不推荐它,因为它不利于可读性:

this.finalObject.properties.push({
    'key': row[0],
    'value': row[1],
    'categories': condition ? trueValue : falseValue,
});


推荐阅读