嗨,我有这个带对象的数组,
[
{
"QuestionID":1350,
"Answers":[
{
"AnswerId":"1350_1",
"selected":true
},
{
"AnswerId":"1350_2",
"selected":false
},
{
"AnswerId":"1350_3",
"selected":false
}
]
},
{
"QuestionID":1349,
"Answers":[
{
"AnswerId":"1349_1",
"selected":false
},
{
"AnswerId":"1349_2",
"selected":true
},
{
"AnswerId":"1349_3",
"selected":false
}
]
}
]
但应更改为此,其中answerID是选定的答案ID
[
{
"QuestionID": 1350,
"AnswerId": "1350_1"
},
{
“QuestionID”: 1349,
“AnswerId”: "1349_2"
}
]
答案 0 :(得分:4)
你可以这样做:
data.map(item => ({
QuestionID: item.QuestionID,
AnswerId: item.Answers.find(answer => answer.selected).AnswerId,
}));
答案 1 :(得分:0)
试试这个
arr.map( s => (s.AnswerId = s.Answers.find( p => p.selected ).AnswerId, delete s.Answers, s) )
解释
selected == true
answers
密钥演示
var input = [{
"QuestionID": 1350,
"Answers": [{
"AnswerId": "1350_1",
"selected": true
},
{
"AnswerId": "1350_2",
"selected": false
},
{
"AnswerId": "1350_3",
"selected": false
}
]
},
{
"QuestionID": 1349,
"Answers": [{
"AnswerId": "1349_1",
"selected": false
},
{
"AnswerId": "1349_2",
"selected": true
},
{
"AnswerId": "1349_3",
"selected": false
}
]
}
];
var output = input.map(s => (s.AnswerId = s.Answers.find(p => p.selected).AnswerId, delete s.Answers, s));
console.log(output);