I have an array with an object inside that houses more objects that I would like to map to a simpler structure.
I have tried with the following and it seems to loop through the objects and return a single object for each loop with no data.
Object.values(data).forEach((a) => {
console.log({
managingRole: a.id === 110 ? a.answer : null,
advice: a.id === 112 ? a.answer : null,
});
});
The end goal is to return an array of object to map through like:
const desired = [{
managingRole: 'spending',
advice: 'everyone'
},
{
managingRole: 'saving',
advice: 'no one'
}];
The data I an working with is below:
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'
}
}];
Array#map()? A web search for "javascript map array" would have had this right at the top along with numerous questions on this site alsoObject.values(data)to loop over an array. Just usedata.forEach().Array#filter()to remove the elements that you don't need in the result.idproperty.Object.values(a)[0]to get the property in the object. Why do you have an array of objects where each object has a different key?