how to push the object keys and values to array

I need to push the key value pair to new array and should build the mongodb $match query.

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


const payload = {
    id :1,
    name : 'Alfred',
    location : 'moon'
}
queryFormat(payload)

expected output

{"$match":{"$and":[{id:1},{name:"Alfred"},{location:"moon"}]}}

output I got

{"$match":{"$and":[{key:1},{key:"Alfred"},{key:"moon"}]}}

How to deal with it
Thanks!!

37 thoughts on “how to push the object keys and values to array”

  1. Currently you are specifying the key as "key"

    Use [] to specify that you need the value of key as the key

    const queryFormat = (payload) => {
        delete payload.userEventId
        var query = {}
         var res = []
        for(key in payload) {
           res.push({ [key]: payload[key] })
        }
        query['$match'] = {"$and" :res}
        console.log(query)    
    }
    
    
    const payload = {
        id :1,
        name : 'Alfred',
        location : 'moon'
    }
    queryFormat(payload)
    Reply

Leave a Comment