Say I have an object as follows:
const data = {
title: 'firstStackOverFlowQuestion!',
id: '100',
datePosted: '04-10-2022',
options: [
{
questionId: 1,
difficultyLevel: 1,
difficultyScale: 10,
complexity: 2,
complexityScale: 10,
},
{
questionId: 2,
difficultyLevel: 4,
difficultyScale: 10,
complexity: 3,
complexityScale: 10,
},
{
questionId: 3,
difficultyLevel: 8,
difficultyScale: 10,
complexity: 6,
complexityScale: 10,
},
]
}
What is the cleanest way to reduce the options array to just two properties, to show the below:
const data = {
title: 'firstStackOverFlowQuestion',
id: '100',
datePosted: '04-10-2022',
options: [
{
questionId: 1,
difficultyLevel: 1,
},
{
questionId: 2,
difficultyLevel: 4,
},
{
questionId: 3,
difficultyLevel: 8,
},
],
}
Any suggestions would be most welcome! I imagine mapping, reducing, and /or using the spread operator would offer the cleanest solutions.
CodePudding user response:
As you said, map
...
(spread):
const result = {
...data,
options: data.options.map(
({questionId, difficultyLevel}) => ({questionId, difficultyLevel})
)
}
CodePudding user response:
Use map()
along with destructuring.
data.options = data.options.map(
({questionId, difficultyLevel}) => ({questionId, difficultyLevel})
);