鉴于以下数据,我想为每个字段提取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"
}
]
}
}
答案 0 :(得分:1)
为此,您可以使用Object.keys
遍历输入对象的键,并使用Array.prototype.map
和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);