我编写了一段代码,将数据集的值映射到新对象。
我想在将数据分配给新的对象变量之前检查数据集中的一个变量。为此,我将使用if条件。如何使用Typescript中的地图实现此目的。如果我尝试编译,以下代码将返回错误。
如果我尝试在console.log行中执行if条件,它只会影响数据集中的第一项。
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,
}));
答案 0 :(得分:0)
基本语法问题。更改您的地图代码如下
data.result = <any> data.result.map((user, index) => {
if (user.name === null || user.name === undefined) {
}
return {
id: user.id,
name: user.name,
type: user.type,
password: user.password,
}
});
或者,使用三元运算符
data.result = <any> data.result.map((user, index) => ({
id: user.id,
name: (user.name === null || user.name === undefined) ? "???" : user.name,
type: user.type,
password: user.password,
}));
不确定我需要放置"???"
的位置 - 因为在条件为真时您没有显示该怎么做