What I am trying to do is fetch details from Db and while I get the response,the attributes name shouldn't be same as the Db so for that I am using for loop. WHile i try to console it I am getting desired response but I am getting empty array/the last data of the db. Can anyone help me out?
// ------display all customer group---->
const displayCustomerGroup = async (req,res,next) =>{
var results = await Group.findAll();
var newData ={};
var data = {};
for(var i = 0; i < results.length ; i++){
for(const [key,value] of Object.entries(results[i].dataValues)){
newData[key.replace("cg_","")] = value;
}
console.log(newData)
}
res.json({
status:"success",
message:"Successfully",
data:newData
})
}
It seems like you have two loops: you have many results (which you iterate over in the outer loop), and each result has a set of many key-value pairs (which you iterate through in the inner loop). The inner loop is copying the key-value pairs into newData
, but if the next result has the same key names, they will overwrite the previous result's data.
Instead, you need to use an array of objects, and fill that list item by item in the outer loop:
var dataList =[];
for(var i = 0; i < results.length ; i++){
let dataItem = {};
for(const [key,value] of Object.entries(results[i].dataValues)){
dataItem[key.replace("cg_","")] = value;
}
dataList.push(dataItem);
}
res.json({
status:"success",
message:"Successfully",
data: dataList
})