'How to delete an array attribute for all values in node js?
I want to return all users in JSON format except their passwords. To do so, I have done something like this
try {
const rawResults = await model.find(query).limit(limit).skip(startIndex)
results.results = rawResults.forEach((v) => delete v.password)
} catch (error) {
results.error = error
}
now when I am trying to console.log the result value, it always returns
{ next: null, results: undefined }
Please help me fix this issue. Thank you so much.
Solution 1:[1]
ForEach modifies the original object.
If you don't need rawResults any more (hopefully, as passwords should be encrypted as Nick pointed out), you can use your code as follows:
try {
const rawResults = await model.find(query).limit(limit).skip(startIndex)
rawResults.forEach((v) => delete v.password)
results.results = rawResults
} catch (error) {
results.error = error
}
If you need separate RawResults and result objects you can use map instead of forEach:
try {
const rawResults = await model.find(query).limit(limit).skip(startIndex)
results.results = rawResults.map(({password, ...v}) => v)
} catch (error) {
results.error = error
}
Solution 2:[2]
Array.prototype.forEach returns undefined.
Just call rawResults.forEach((v) => delete v.password) without the results.results = and your code will work.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | marc_s |
| Solution 2 | Samathingamajig |
