How to push the key and values to array and build the dynamic query?

I needs to build the query object for mongodb. while tired this I got the output like this,

output

{"$match":{"$and":[{id:1},{name:"Alfred"},{location:"moon"},{"values":{"$in":[{name:"u",age: 9}]} }]}}

this my code,

const queryFormat = (payload) => {
    delete payload.userEventId
    var query = {}
     var res = []
    for(key in payload) {
        if(typeof(payload[key])) {
       res.push({ [key]: payload[key] })
        }
        else {
            res.push({"$in" :{ [key]: payload[key] }})
        }
    }
    console.log(res[3])
    query['$match'] = {"$and" :res}
    console.log(query)    
}


const payload = {
    id :1,
    name : 'Alfred',
    location : 'moon',
    values : [{name: 'u',age:9}]
}
queryFormat(payload)

expected output

{"$match":{"$and":[{id:1},{name:"Alfred"},{location:"moon"},{"values":{"$in":[{name:"u"},{age: 9}]} }]}}

Thanks!

18 thoughts on “How to push the key and values to array and build the dynamic query?”

Leave a Comment