我有一个数组,里面有一个对象,其中包含更多我想映射到更简单结构的对象。
我尝试了以下方法,它似乎遍历对象并为每个没有数据的循环返回一个对象。
Object.values(data).forEach((a) => {
console.log({
managingRole: a.id === 110 ? a.answer : null,
advice: a.id === 112 ? a.answer : null,
});
});
最终目标是返回要映射的对象数组:
const desired = [{
managingRole: 'spending',
advice: 'everyone'
},
{
managingRole: 'saving',
advice: 'no one'
}];
我正在使用的数据如下:
const data = [{
'110':
{
id: 110,
type: 'RADIO',
question: '<strong>My main role in managing my money is:</strong>',
section_id: 9,
answer: 'spending'
},
'111':
{
id: 111,
type: 'RADIO',
question: '<strong>When it comes to financial matters, I most agree with which statement?</strong>',
section_id: 9,
answer: 'spend it'
},
'112':
{
id: 112,
type: 'RADIO',
question: '<strong>When deciding on an investment, I trust the advice of :</strong>',
section_id: 9,
answer: 'everyone'
}
},
{
'110':
{
id: 110,
type: 'RADIO',
question: '<strong>My main role in managing my money is:</strong>',
section_id: 9,
answer: 'saving'
},
'111':
{
id: 111,
type: 'RADIO',
question: '<strong>When it comes to financial matters, I most agree with which statement?</strong>',
section_id: 9,
answer: 'save it'
},
'112':
{
id: 112,
type: 'RADIO',
question: '<strong>When deciding on an investment, I trust the advice of :</strong>',
section_id: 9,
answer: 'no one'
}
}];
答案 0 :(得分:1)
您可以直接使用给定的id
寻址对象,这与具有想要的answer
的对象的键相同。
const
data = [{ 110: { id: 110, type: 'RADIO', question: '<strong>My main role in managing my money is:</strong>', section_id: 9, answer: 'spending' }, 111: { id: 111, type: 'RADIO', question: '<strong>When it comes to financial matters, I most agree with which statement?</strong>', section_id: 9, answer: 'spend it' }, 112: { id: 112, type: 'RADIO', question: '<strong>When deciding on an investment, I trust the advice of :</strong>', section_id: 9, answer: 'everyone' } }, { 110: { id: 110, type: 'RADIO', question: '<strong>My main role in managing my money is:</strong>', section_id: 9, answer: 'saving' }, 111: { id: 111, type: 'RADIO', question: '<strong>When it comes to financial matters, I most agree with which statement?</strong>', section_id: 9, answer: 'save it' }, 112: { id: 112, type: 'RADIO', question: '<strong>When deciding on an investment, I trust the advice of :</strong>', section_id: 9, answer: 'no one' } }],
result = data.map(o => ({
managingRole: o['110'].answer || null,
advice: o['112'].answer || null
}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }