打字稿-如果地图内有条件 [英] Typescript - if conditrional inside a map

查看:59
本文介绍了打字稿-如果地图内有条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将用户数据的子集映射到精炼数据集的对象。在地图内部,我想检查变量是否为null或未定义,如果是,则将此变量设置为占位符值。

I am mapping a subset of user data to an object of a refined data set. Inside the map i want to check if a variable is null or undefined, and if yes, then to set this variable to a placeholder value.

我面临的问题是在地图内部声明if语句会导致错误,但是即使地图可以将索引作为参数,我们如何在功能上与条件语句一起使用?

The issue I am facing is that declaring an if statement inside the map is causing an error, but even though a map can have an index as a parameter, how can we use it functionally with a conditional Statement? Any insight most appreciated.

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


推荐答案

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

You're attempting to use an object literal as the return type, but naturally, an if statement (or any statement) can't be inside object literal syntax.

因此,请定义一个函数主体,该主体也使用花括号,然后使用显式的 return 语句将代码放入内部。

So instead, define a function body, which also uses curly braces, and put your code inside with an explicit return statement.

// 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, 
  */
});

这篇关于打字稿-如果地图内有条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆