通过键提取对象数组中的内容

时间:2018-07-31 10:36:11

标签: javascript arrays javascript-objects

鉴于以下数据,我想为每个字段提取2个值,字段名称和所选值。也许使用Map吗?

"form_details": {
    "age": {
      "options": [
        {
          "label": "18 yrs",
          "value": "18"
        },
        {
          "label": "21 yrs",
          "selected": true,
          "value": "21"
        }
      ]
    },
    "sex": {
      "options": [
        {
          "label": "male",
          "value": "m"
        },
        {
          "label": "female",
          "selected": true,
          "value": "f"
        }
      ]
    }    
 }

1 个答案:

答案 0 :(得分:1)

为此,您可以使用Object.keys遍历输入对象的键,并使用Array.prototype.mapArray.prototype.find将它们映射到选定的值:

const form_details={"age":{"options":[{"label":"18 yrs","value":"18"},{"label":"21 yrs","selected":!0,"value":"21"}]},"sex":{"options":[{"label":"male","value":"m"},{"label":"female","selected":!0,"value":"f"}]}}

 const result = Object.keys(form_details).map(field => {
    return {
        field,
        selected: form_details[field].options.find(o => o.selected).value
    }
 })

 console.log(result);