Reputation: 458
i try loop data into empty object but it turns out the data after i console.log the data only return one object wher, can someone tell me where i did wrong here
const data_warehouse = forms.map((item) => {
item.answer.map((data) => {
let data_fix = {};
Object.keys(data.answers).map((key) => {
return (data_fix = {
[key.replace(/ /g, "_").toLowerCase()]: data.answers[key],
});
});
console.log(data_fix);
});
});
here is the data from mongoDB:
"forms": [
{
"_id": "Quality",
"title": "Quality",
"answer": [
{
"username": "[email protected]",
"date": "2022-10-25",
"formId": "6357921d49de88bb7fffcfe4",
"answers": {
"Text": "[email protected]",
"Email": "[email protected]",
"Plant": "Cica"
}
},
{
"username": "[email protected]",
"date": "2022-10-25",
"formId": "6357921d49de88bb7fffcfe4",
"answers": {
"Email": "[email protected]",
"Plant": "Ranca",
"Text Doang": "12"
}
},
{
"username": "[email protected]",
"date": "2022-10-31",
"formId": "6357921d49de88bb7fffcfe4",
"answers": {
"Text": "[email protected]",
"Email": "[email protected]",
"Plant": "Cica"
}
}
]
}
]
i try to redesign the key on field "answers" to change all the specials characters into underscore, but its only returning one data after i loop it into map function:
{ plant: 'Cica' }
{ text_doang: '12' }
{ plant: 'Cica' }
my expected result should be like this,it will return the same format but only cleanup the special characters from the key on field "answers":
[
{
"_id": "Quality",
"title": "Quality",
"answer": [
{
"username": "[email protected]",
"date": "2022-10-25",
"formId": "6357921d49de88bb7fffcfe4",
"answers": {
"text": "[email protected]",
"email": "[email protected]",
"plant": "Cica"
}
},
{
"username": "[email protected]",
"date": "2022-10-25",
"formId": "6357921d49de88bb7fffcfe4",
"answers": {
"email": "[email protected]",
"plant": "Ranca",
"text_doang": "12"
}
},...etc]
Upvotes: 0
Views: 20
Reputation: 10429
try this
var forms=[
{
"_id": "Quality",
"title": "Quality",
"answer": [
{
"username": "[email protected]",
"date": "2022-10-25",
"formId": "6357921d49de88bb7fffcfe4",
"answers": {
"Text": "[email protected]",
"Email": "[email protected]",
"Plant": "Cica"
}
},
{
"username": "[email protected]",
"date": "2022-10-25",
"formId": "6357921d49de88bb7fffcfe4",
"answers": {
"Email": "[email protected]",
"Plant": "Ranca",
"Text Doang": "12"
}
},
{
"username": "[email protected]",
"date": "2022-10-31",
"formId": "6357921d49de88bb7fffcfe4",
"answers": {
"Text": "[email protected]",
"Email": "[email protected]",
"Plant": "Cica"
}
}
]
}
]
var newData= forms.map((item) => {
var mappedAns=item.answer.map((data) => {
let data_fix = {};
Object.keys(data.answers).forEach((key) => {
data_fix[key.replace(/ /g, "_").toLowerCase()]= data.answers[key];
});
return {...data,answers:data_fix};
});
return {...item,answer:mappedAns}
});
console.log(newData);
Upvotes: 1