如何在JavaScript中简化这一点?



我想把一个对象转换成一个特定的数组。

这是我的例子对象:

const object = {
details: 'Here are some details',
info: 'Here is a bit of info',
more: 'Wanna see more?',
random: 'Title 4',
random2: 'Title 5',
...
}

我想要下面的输出:

[
{
"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 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
}
]

由于需要映射到具体的键,所以不需要迭代,所以我认为是这样清除的。

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相同的长度

你可以在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; }

相关内容

最新更新