我正在寻找一种方法来访问“健康”和“健康”。和' gif'我的对象内的键。现在,我只能在页面上显示一个或另一个 - ' fit'作为一个形象和' gif'是一个GIF。
我想我可能会使用.match,但我并不确定正确的语法
由于
const sizeMappings = {
master: '1280',
small: '192w',
small_fit: '192w',
medium: '384w',
medium_low_res: '288w',
medium_fit: '384w',
medium_gif: '384w',
medium_fit_low_res: '288w',
large: '768w',
large_fit: '768w',
large_gif: '768w',
xlarge: '1280w',
xlarge_fit: '1280w',
}
const getSrcSet = (renditions, fit, gif) => {
const sizes = Object.keys(sizeMappings)
.map((key) => {
if (fit && !key.includes('fit')) return null
const mapping = `${renditions[key]} ${sizeMappings[key]}`
return mapping
})
return sizes
.filter(el => el !== null)
.join(',')
}
答案 0 :(得分:1)
我会使用filter()
而不是map()
,因为您实际上想要提取数组的子集。然后,只需将每个键匹配为给定的大小名称+ "_gif"
或大小名称+ "_fit"
。
const sizeMappings = {
master: '1280',
small: '192w',
small_fit: '192w',
medium: '384w',
medium_low_res: '288w',
medium_fit: '384w',
medium_gif: '384w',
medium_fit_low_res: '288w',
large: '768w',
large_fit: '768w',
large_gif: '768w',
xlarge: '1280w',
xlarge_fit: '1280w',
}
let size = "large"; //change me
let arr = Object.keys(sizeMappings).filter(
(key) => (key === size + "_fit" || key === size + "_gif")
);
console.log(arr)

答案 1 :(得分:0)
首先过滤然后根据需要映射结果:
const getSrcSet = (renditions, fit, gif) => {
return Object.keys(sizeMappings)
.filter(key => fit && key.includes('fit') || gif && key.includes('gif'))
.map(key => `${renditions[key]} ${sizeMappings[key]}`)
.join(',')
}