4 回答
TA贡献2021条经验 获得超8个赞
您不需要过滤和连接 - 这不会对性能产生不必要的影响。
join如果您需要使用和功能的答案,filter@Ever Dev 的答案非常好
var sorted = [ {firstName: "john", lastName: "Doe", age: 36, gender: "male"},
{lastName: "Latt", age: 40, gender: "male"},
{firstName: "Tom", age: 22, gender: "male"}
]
var result = sorted.map(val => (`${val.firstName ? val.firstName: ''} ${val.lastName? val.lastName: ''}`).trim() )
//.join(' ');
console.log(result);
TA贡献1831条经验 获得超4个赞
const sort = [
{firstName: "john", lastName: "Doe", age: 36, gender: "male"},
{lastName: "Latt", age: 40, gender: "male"},
{firstName: "Tom", age: 22, gender: "male"}
];
console.log(
sort.map(item =>
[item.firstName, item.lastName].filter(v => !!v).join(' ')
))
TA贡献1830条经验 获得超9个赞
你要找的是地图()
> sorted.map(user => {
> if (user.firstName && user.lastName) return user.firstName + " " +
> user.lastName
> if (user.firstName) return user.firstName
> if (user.lastName) return user.lastName
> return ""
> })
TA贡献1802条经验 获得超5个赞
您将需要.map()
每个项目并应用您的逻辑
sorted.map(person => { return `${person.firstName}${person.firstName && person.lastName ? ' ' : ''}${person.lastName}`; });
添加回答
举报