Search code examples
javascriptarraysjavascript-objects

Extracting by key in an array of objects


Given the following data, I'd like to extract 2 values for each field, the name of the field and the selected value. Maybe using 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"
        }
      ]
    }    
 }


Solution

  • For this you can iterate over the keys of your input object with Object.keys and map them out to selected values with Array.prototype.map and Array.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);