[英]How to simplify this in JavaScript?
我想将 object 转换为特定数组。
这是我的示例 object:
const object = {
details: 'Here are some details',
info: 'Here is a bit of info',
more: 'Wanna see more?',
random: 'Title 4',
random2: 'Title 5',
...
}
我想要以下 output:
[
{
"tabLabel": "Some details", // details
"tabContent": "Here are some details"
},
{
"tabLabel": "Explanations", // info
"tabContent": "Here is a bit of info"
},
{
"tabLabel": "Continue your journey", // more
"tabContent": "Wanna see more?"
}
]
我采用的解决方案:
const newObj = Object.entries(object).map(([key, val]) => {
if (key === 'details') {
dataArray.push({ tabLabel: "Some details", tabContent: val });
}
if (key === 'info') {
dataArray.push({ tabLabel: 'Explanations', tabContent: val });
}
if (key === 'more') {
dataArray.push({ tabLabel: 'Continue your journey', tabContent: val });
}
});
我怎样才能更优雅地做到这一点?
const object = {
details: 'Here are some details',
info: 'Here is a bit of info',
more: 'Wanna see more?'
}
const signification = {
details: "Some details",
info: "Explanations",
more: "Continue your journey"
}
const array = Object.entries(object).map (x => {
return {
tabLabel: x[1],
tabContent: signification[x[0]]
}
})
console.log(array)
结果符合:
[{
tabContent: "Some details",
tabLabel: "Here are some details"
}, {
tabContent: "Explanations",
tabLabel: "Here is a bit of info"
}, {
tabContent: "Continue your journey",
tabLabel: "Wanna see more?"
}]
你只需要实现signification
,他需要和object
有相同的长度
怎么样
const newObj = [ // In fact is an Array
{
"tabLabel": "Some details",
"tabContent": object.details
},
{
"tabLabel": "Explanations", // info
"tabContent": object.info
},
{
"tabLabel": "Continue your journey", // more
"tabContent": object.more
}
]
由于您需要 map 来具体键,因此无需迭代,因此我认为通过这种方式清除。
您可以在 JavaScript 上使用 Map 并使代码更清晰。
const object = {
details: 'Here are some details',
info: 'Here is a bit of info',
more: 'Wanna see more?',
random: 'Title 4',
random2: 'Title 5',
};
const label = new Map()
.set('details', "Some details")
.set('info', "Explanations")
//so on
;
const array = Object.entries(object).map(([key, val]) => {
return {
tabLabel: label.get(key),
tabContent: val
};
})
console.log(array)
类似的东西?
const obj = { details: 'Here are some details', info: 'Here is a bit of info', more: 'Wanna see more?' } const Labels = { details: 'Some details', info: 'Explanations', more: 'Continue your journey' } const newObj = Object.entries(obj).map(([k, v],i) =>({ tabLabel:Labels[k], tabContent:v} )) console.log( newObj )
.as-console-wrapper { max-height: 100%;important: top; 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.