遍历状态对象并更改值

时间:2020-06-25 22:09:47

标签: javascript reactjs ecmascript-6

我有一个如下所示的对象,具有一些状态和其他键值对

-E

我需要遍历该对象并将状态从sectionStatus: { airSystemsSectionNotesHTML: "" airSystemsSectionStatus: "NOT_STARTED" codesAndGuidelinesSectionNotesHTML: "" codesAndGuidelinesSectionStatus: "NOT_STARTED" executiveSummarySectionNotesHTML: "" executiveSummarySectionStatus: "NOT_STARTED" exhaustEquipmentSectionNotesHTML: "" exhaustEquipmentSectionStatus: "NOT_STARTED" ...... // some other status ...... } 更改为NOT_STARTED,在React JS中有什么有效的方法吗?

请让我知道如何有效地实现这一目标吗?

非常感谢

2 个答案:

答案 0 :(得分:2)

您可以遍历对象的可枚举属性,选中值为“ NOT_STARTED”的对象,然后切换:

const obj = {
  sectionStatus: {
    airSystemsSectionNotesHTML: "",
    airSystemsSectionStatus: "NOT_STARTED",
    codesAndGuidelinesSectionNotesHTML: "",
    codesAndGuidelinesSectionStatus: "NOT_STARTED",
    executiveSummarySectionNotesHTML: "",
    executiveSummarySectionStatus: "NOT_STARTED",
    exhaustEquipmentSectionNotesHTML: "",
    exhaustEquipmentSectionStatus: "NOT_STARTED"
  }
}

const res = Object.fromEntries(
  Object.entries(obj.sectionStatus)
  .map(([k, v]) => ([k, v === "NOT_STARTED" ? "COMPLETED" : v]))
)

console.log(res)

答案 1 :(得分:1)

(在我眼中)可读性更高

const obj = 
  { sectionStatus :
    { airSystemsSectionNotesHTML:         ''
    , airSystemsSectionStatus:            'NOT_STARTED'
    , codesAndGuidelinesSectionNotesHTML: ''
    , codesAndGuidelinesSectionStatus:    'NOT_STARTED'
    , executiveSummarySectionNotesHTML:   ''
    , executiveSummarySectionStatus:      'NOT_STARTED'
    , exhaustEquipmentSectionNotesHTML:   ''
    , exhaustEquipmentSectionStatus:      'NOT_STARTED'
    // ......   some other status
    // ...... 
  } }

for (let st in el=obj.sectionStatus)
  {
  if (el[st]==='NOT_STARTED') el[st]='COMPLETE'
  }

console.log ( obj.sectionStatus )
.as-console-wrapper { max-height: 100% !important; top: 0; }