Home > database >  MongoDB get specific key from document based on given value
MongoDB get specific key from document based on given value

Time:02-03

I am getting a Document as:

async findOne(id: string) {
    return await this.gameModel.findById(id);
}

async update(id: string, updateGameDto: UpdateGameDto) {
    const game = await this.findOne(id)

    // This gives all keys as expected
    for( const key in game){
        console.log(key)
    }
    // ...
    const keys = Object.keys(game) // [ '$__', '$isNew', '_doc' ]
    return;

}

Why does Object.keys(game) only return those 3 keys? If it only returns those keys, obviously I can't get the key as so:

const specificKeyByValue = Object.keys(game).find(key => game[key] === "SomeValue")

I could create a function that simply returns the key with a for loop like;

const getKeyByValue = (obj, value) => 
{
    for( const key in obj)
    {
        if(obj[key] === value) return key;
    }
}

But I prefer to stay away from creating extra functions if I don't have to. Any idea why this Object.Keys() variant doesn't work?

CodePudding user response:

There are few differences in behaviour of Object.keys and for-in.

for-in iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.

As per the MDN docs this is what for-in does:

The loop will iterate over all enumerable properties of the object itself and those the object inherits from its prototype chain (properties of nearer prototypes take precedence over those of prototypes further away from the object in its prototype chain).

A for...in loop only iterates over enumerable, non-symbol properties. Objects created from built–in constructors like Array and Object have inherited non–enumerable properties from Array.prototype and Object.prototype, such as Array's indexOf() method or Object's toString() method, which will not be visited in the for...in loop.

And the difference (docs)

Object.keys() returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon object. This is the same as iterating with a for...in loop, except that a for...in loop enumerates properties in the prototype chain as well. The order of the array returned by Object.keys() is the same as that provided by a for...in loop.

Check few examples here

CodePudding user response:

const getKeyByValue = (obj, value) => { for( const key in obj) { if(obj[key] === value) return key; } }

  • Related