![](/img/trans.png)
[英]Javascript trying to sort array of objects based on inner object array values
[英]trying to loop through inner object and changing the values based on condition
下面是我試圖根據一些值修改的 object 結構
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: ''
}
});
我正在根據條件修改description
值並嘗試返回相同的 object 結構,但無法通過此操作並獲得類似於 If 語句中expression expected
的錯誤。
Object.entries(PROJECT_PHASE).forEach(([key,value]) => (
if(value.stepNumber === currentStepNumber){
value.description = 'Current';
}
));
任何人都可以幫助解決這個問題,我怎樣才能修改內部 object? 非常感謝 !!!!
您會看到該錯誤,因為在您的 forEach 中您使用的是()
而不是{}
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)
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);
這將創建根據需要修改的PROJECT_PHASE
object 的副本。 注意使用map
而不是forEach
並將結果輸入Object.fromEntries
你cab用這種方式,你的代碼有錯誤。 我在這里使用 currentStepNumber 是 3
Object.entries(PROJECT_PHASE).forEach(([key,value]) => {
if(value.stepNumber === 3){
value.description = 'Current';
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.