1

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());
        })
Mo1
  • 369
  • 7
  • 18
  • you have an array with one object. Is that what you intended, or where each key:value pair is an element? – OldProgrammer Aug 16 '19 at 22:40
  • That said, it's generally best to not rely on property order in the first place, and make your code that depends on it more flexible instead. – John Montgomery Aug 16 '19 at 22:43
  • @OldProgrammer, I intend to have many objects inside the **mentors** array with an incremental **mentorId**. – Mo1 Aug 17 '19 at 06:10

1 Answers1

3

Object properties can't always be depended on to be ordered. Sometimes they can be, but often they aren't (such as with JSON serialization/deserialization, Object.keys, and for..in loops).

If you're using a method that in ES6+ does have a guaranteed order for iterating over keys (like Reflect.ownKeys, object rest/spread, Object.assign, Object.getOwnPropertyDescriptors, Object.getOwnPropertyNames, and so on - look up uses of OwnPropertyKeys), then the other keys will have to be added after the mentorId key has been added. While this could be done with mutation via some messy deletes, creating an entirely new object for that place in the array would probably be a lot cleaner:

const 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
        }
    ]
};

const { id, ...rest } = body.data[0];
body.data[0] = {
  mentorId: id,
  ...rest
};
console.log(body.data);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • I upvoted the answer but I still have less than 15 reputation because I've just started interacting with the dev community here and you know my upvote won't change the votes publicly. – Mo1 Aug 19 '19 at 08:02