[英]conditionally return an object-property in javascript
所以这可能看起来像一个奇怪的问题,但请耐心等待:
我有一个简单的字符串数组,我想将它映射到一个对象数组。 很简单:我会写
arr.map (x => ({
header : x,
sortType: 'basic'
}))
现在,问题来了:我想检查一下 x 是否具有特定值,然后根本不包括 sortType。 我想做类似的事情
arr.map (x => ({
header : x,
x==='test' ? (sortType: 'basic') : //don't provide anything
}))
所以我希望我的最终数组是这样的:我当然不想有两张地图!
[
{ header: 'Header One' , sortType: 'basic'},
{ header: 'test' },
{ header: 'Another one' , sortType: 'basic'},
]
您可以将两个对象与条件运算符一起使用。
arr.map(header => header === 'test'
? { header }
: { header, sortType: 'basic' }
)
arr.map(header => Object.assign({ header }, header !== 'test' && { sortType: 'basic' }))
您可以使用扩展 ( ...
) 表达式,有条件地评估为必要的子对象 ( {sortType: 'basic'}
):
const src = ['Header One','test','Another one'], result = src.map (header => ({ header, ...(header!=='test' && {sortType: 'basic'}) })) console.log(result)
.as-console-wrapper{min-height:100%;}
var arr = ['test','love','javascript'];
const output = arr.map (x => {
const obj = {
header : x
};
if(x === "test") obj.sortType = "basic";
return obj;
});
console.log(output);
// [{header: "test", sortType: "basic"}, {header: "love"}, {header: "javascript"}]
我知道您已经得到了一些不错的答案,以防您更喜欢这种方法。
const arr = ['penguinsinpijamas', 'test'];
var mappy = arr.map(x => {
let obj = {'header': x};
if (obj.header === 'test') obj.sortType = 'basic';
return obj})
mappy.forEach(m => console.log(m))
返回:
Object {header: "penguinsinpijamas"}
Object {header: "test", sortType: "basic"}
尝试这个
var arr = ['test','love','javascript']; var result = arr.map (x => ({ header : x, sortType: x==='test'?undefined:'basic' })) console.log(JSON.stringify(arr)); console.log(JSON.stringify(result));
输出 :
["test","love","javascript"]
[{"header":"test"},{"header":"love","sortType":"basic"},{"header":"javascript","sortType":"basic"}]
您应该为该值应用逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.