I am trying to add the quoteValue key-value in an element (an object in this case) of the users array using the code below.
When I print out console.log(users[0]), it's not showing the value of quoteValue for users[0]. However, console.log(users[0].quoteValue) prints the actual value of quoteValue.
I don't understand how it is possible. It would really appreciate your help!
export async function get_client_users(req, res) { try { let users = await User.find({ role: { $eq: 'client' }, status: { $ne: 'deleted' } }, { name: 1, mobile: 1, email: 1, status: 1, ref_id : 1, _id: 1 }); for(let i = 0; i < users.length; i += 1) { let quotes = await Quote.find({client: users[i]._id}); const totalQuote = quotes.length; let cost = 0; for(let i = 0; i < quotes.length; i += 1) { cost += quotes[i].total_cost; } const result = { totalQuote: totalQuote, quoteValue: cost } Object.assign(users[i], result); } return res.status(200).json(users); } catch(e) { console.log(e); return res.status(400).json({ message: 'Technical Error. Please try again later.' }); }; };
Object.assign(users[i], result);? What do you want that array element to look like? And, is there any reason you don't just dousers[i].totalQuote = totalQuote;andusers[i].quoteValue = cost;?console.log('user =>', users[0])doesn't work? Where did you put that line of code? It's possible that some properties are configuredenumerable: falseand thus won't show inconsole.log(users[0]), but will show inconsole.log(users[0].property). You can test that for sure withObject.getOwnPropertyNames(users[0])to see every property that's actually there regardless of enumerability.quoteValueandtotalQuotewith users in response, how I can send this