is there any way of moving key:value pair from one position to another inside an object? I knew this on arrays and I Googled , in vain, an easy way to do it.
I renamed a key from "id" to "mentorId" and it took the last position yet I want to be on the first position.
The code for renaming
value['mentorId'] = value['id'];
delete value['id'];
My response body
{
"status": 200,
"message": "All Mentors",
"data": [
{
"first_name": "Brick",
"last_name": "Ken",
"email": "brick@gmail.com",
"address": "kigali",
"bio": "so successful",
"occupation": "army",
"expertise": "3 years",
"is_admin": false,
"is_mentor": true,
"mentorId": 2
}
]
}
Everything else is fine except this index issue. I would appreciate your help. Thanks.
PROBLEM SOLVED
I recently asked this question and thanks to the help of you all good devs I used your input, searched the internet and finally found the solution. Here is how I implemented what I wanted in this allMentors static method:
static async allMentors(req, res) {
try {
users.forEach(user => {
if(user.is_mentor === true) {
mentors.push(user);
}
})
const ObjKeyRename = (src, map) => {
const dst = {};
for (const key in src) {
if (key in map)
// rename key
dst[map[key]] = src[key];
else
// same key
dst[key] = src[key];
}
return dst;
};
const uniqueMentors = Array.from(new Set(mentors.map(m => m.id)))
.map(id => {
return new Promise((resolve, reject)=> {
const currMentor = mentors.find(m => m.id === id);
const modMentor = ObjKeyRename(currMentor, { "id": "mentorId" });
return resolve(modMentor);
})
})
Promise.all(uniqueMentors).then(output => {
output.forEach(async obj => {
await delete obj['password'];
})
return res
.status(200)
.json(new ResponseHandler(200, 'All Mentors', output, null).result());
})