JS中从数组对象中提取需要的某些字段

 有一个数组questions

questions: [
  {
    id: 348
    question: "以下哪些机体属于基拉大和?"
    createTime: "2020-03-30T02:16:44.000+0000"
    createUser: "系统管理员"
    updateTime: "2020-03-30T02:16:43.000+0000"
    type: 2
    createUserId: 1
    questionOptions: [
        0: {id: 529, identifier: "A", content: "自由高达", sortNum: 0, value: 529, label:     "A、自由高达"}
        1: {id: 530, identifier: "B", content: "脉冲高达", sortNum: 1, value: 530, label: "B、脉冲高达"}
        2: {id: 531, identifier: "C", content: "强袭高达", sortNum: 2, value: 531, label: "C、强袭高达"}
        3: {id: 532, identifier: "D", content: "正义高达", sortNum: 3, value: 532, label: "D、正义高达"}
    ]
  }
]

遍历操作提取自己想要的字段,想得到如下结果:

"questions": [
        {
            "id": 348,
            "question": "以下哪些机体属于基拉大和?",
            "questionOptions": [
                {
                    "id": 529,
                    "content": "自由高达"
                },
                {
                    "id": 530,
                    "content": "脉冲高达"
                },
                {
                    "id": 531,
                    "content": "强袭高达"
                },
                {
                    "id": 532,
                    "content": "正义高达"
                }
            ]
        }
    ],

具体操作如下:

第一步:循环外层数组 (第一种方法)

this.questions = this.questions.map(({ id, question, questionOptions }) => ({ id, question, questionOptions }))
 console.log(this.questions)

第二步:操作内层数组 questionOptions (第二种方法)

       this.questions.forEach(element => {
              element.questionOptions.forEach(ele => {
                delete ele.identifier
                delete ele.sortNum
                delete ele.value
                delete ele.label
          })
        })

 

你可能感兴趣的:(javascript)