【问题标题】:Typescript - if conditrional inside a map打字稿 - 如果地图内有条件
【发布时间】:2018-05-17 02:16:08
【问题描述】:

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

我面临的问题是在 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,
}));

【问题讨论】:

  • 什么错误?而且您不会从内部地图内部返回。
  • 当然你可以在映射函数中使用if 语句。请提供一些示例输入和所需的输出,否则不清楚您要在这里做什么。
  • 请看原帖中的代码。我试图返回{id name type and password}的数据集,但是id首先想在设置之前检查type的值。

标签: javascript typescript dictionary if-statement


【解决方案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】:

    据我所知,仅靠地图是无法做到的。 但是您可以使用 filter() 函数来跟进它:

    const newArray = oldArray.map((value, index) => condition ? value : null).filter(v => v);
    

    您基本上遍历每个项目,然后根据您的条件返回值或 null。 现在,一旦你有了地图,你只需通过从数组中删除空值来过滤它。

    请注意,原始数组没有改变,而是返回了一个新数组。 感谢@user8897421 的想法。我只是想把它变成一个班轮。

    【讨论】:

      【解决方案3】:

      您可以在文字映射中表达条件,但它有点难看。

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

      【讨论】:

      • 用户if else怎么样
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      • 2022-01-22
      • 2021-04-29
      • 1970-01-01
      • 2017-05-09
      • 2021-11-07
      • 2019-05-03
      相关资源
      最近更新 更多