Reputation: 17701
below is my object structure where i am trying to modify based on some values
export const PROJECT_PHASE = Object.freeze({
CONCEPT: { label: 'Concept', stepNumber: 0, disabled: false, description: '' },
SCHEMATIC: { label: 'Schematic', stepNumber: 1, disabled: false, description: '' },
DESIGN_DEVELOPMENT: {
label: 'Design Development',
stepNumber: 2,
disabled: false,
description: ''
},
CONSTRUCTION_DOCUMENTS: {
label: 'Construction Documents',
stepNumber: 3,
disabled: false,
description: ''
}
});
and i am modifying the description
value based on condition and trying to return the same object structure but could not be able to get through this and getting an error like expression expected
at If statement.
Object.entries(PROJECT_PHASE).forEach(([key,value]) => (
if(value.stepNumber === currentStepNumber){
value.description = 'Current';
}
));
Could any please help on this, how can i achieve modify the inner object? many thanks !!!!
Upvotes: 1
Views: 40
Reputation: 2310
const PROJECT_PHASE = Object.freeze({
CONCEPT: { label: 'Concept', stepNumber: 0, disabled: false, description: '' },
SCHEMATIC: { label: 'Schematic', stepNumber: 1, disabled: false, description: '' },
DESIGN_DEVELOPMENT: {
label: 'Design Development',
stepNumber: 2,
disabled: false,
description: ''
},
CONSTRUCTION_DOCUMENTS: {
label: 'Construction Documents',
stepNumber: 3,
disabled: false,
description: ''
}
});
const currentStepNumber = 2;
const alteredEntries = Object.entries(PROJECT_PHASE).map(([key,value]) => {
let newValue = value;
if(value.stepNumber === currentStepNumber){
newValue.description = 'Current';
}
return [key,newValue]
});
const alteredObject = Object.fromEntries(alteredEntries);
console.log(alteredObject);
This will create a copy of the PROJECT_PHASE
object modified as you want. Note the use of map
instead of forEach
and taking the result and feeding it into Object.fromEntries
Upvotes: 2
Reputation: 474
You cab use this way, there is a error in your code. I am using currentStepNumber is 3 here
Object.entries(PROJECT_PHASE).forEach(([key,value]) => {
if(value.stepNumber === 3){
value.description = 'Current';
}
});
Upvotes: 1
Reputation: 4519
You see that error because in your forEach you are using ()
instead of {}
PROJECT_PHASE=Object.freeze({
CONCEPT: { label: 'Concept', stepNumber: 0, disabled: false, description: '' },
SCHEMATIC: { label: 'Schematic', stepNumber: 1, disabled: false, description: '' },
DESIGN_DEVELOPMENT: {
label: 'Design Development',
stepNumber: 2,
disabled: false,
description: ''
},
CONSTRUCTION_DOCUMENTS: {
label: 'Construction Documents',
stepNumber: 3,
disabled: false,
description: ''
}
});
currentStepNumber=3
Object.entries(PROJECT_PHASE).forEach(([key,value]) => {
if(value.stepNumber === currentStepNumber){
value.description = 'Current';
}
});
console.log(PROJECT_PHASE)
Upvotes: 2