简体   繁体   中英

key value pair in javascript

Applying filters in MongoDb

I need to apply filters in mongoDb in an embedded document so how can I make a query like

Example:

var query = {
_id:userId,
'match.Id':matchId,
'match.userId':userId1
}

now I want to apply filters lets suppose

case 1: my query should be like

 var query = {
    _id:userId,
    'match.Id':matchId,

    }

case 2 :

 var query = {
    _id:userId,
    'match.userId':userId1
    }

there can be many cases like this

So my question is how can I make this query object in node.js/javascript

My work : I can create multiple key in an object but creating key as below doesn't works

var query={}
query._id:userId // works
query.'match.userId':matchId // error
query.match.userId:matchId //error

tried below code got desired output but it comes with square bracket but type of arr is object

var arr = [];
arr[ 'key3.abc' ] = "value3";
arr[ 'key2.abc' ] = "value3";
console.log(arr)//[ 'key3.abc': 'value3', 'key2.abc': 'value3' ]

desired output:

{'key3.abc': 'value3', 'key2.abc': 'value3'}

Change [] to {}

 var obj = {}; 
 obj[ 'key3.abc' ] = "value3";       
 obj[ 'key2.abc' ] = "value3"; 

 console.log(obj) // { 'key3.abc': 'value3', 'key2.abc': 'value3'}

NB We can assign or access a JavaScript object by square ( [] ) notation when key contains special character eg space, dot etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM