网站搜索

javascript - Typescript - 在 map 中的 if 条件


我正在将用户数据的一个子集映射到一个精炼数据集的对象中。在映射过程中,我想检查一个变量是否为 null 或 undefined,如果是的话,就将该变量设置为一个占位符值。

我遇到的问题是,在 map 内部声明 if 语句会导致错误,但即使 map 可以将索引作为参数,我们如何在条件语句中功能性地使用它呢?非常感谢任何见解。

return this.UserService.search(url)
.map((data) => {
    console.log(data);
    data.result = <any> data.result.map((user, index) => ({
        // if statement causing error here
        if(user.name === null || user.name === undefined){
            // error with this if condition
        },
        id: user.id,
        name: user.name,
        type: user.type,
        password: user.password,
    }));
    return data;
}).map(data => ({
    meta: { totalItems: data.size },
    data: data.result,
}));

答案#1

你正在尝试将对象字面量用作返回类型,但自然地,if 语句(或任何语句)不能位于对象字面量语法内。

因此,定义一个函数体,它同样使用大括号,并将你的代码放在其中,并显式使用 return 语句。

// Starts function body instead of single expression-v
data.result = <any> data.result.map((user, index) => {

    if (some_condition) {
       return "some value"; // The object?
    } else {
       return "other value"; // A different object?
    }
  /*
    // I assume these are to be used in the object you return
    id: user.id,
    name: user.name,
    type: user.type,
    password: user.password, 
  */
});

答案#2

你可以在字面量映射中表达条件,但这有点丑陋。

return {
 a: 1,
 ...(some_condition && {
  b: 1,
 })
};