Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

I need to build the query object for mongodb. while trying 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!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You need to check is key array or not, if its array then loop and make new array for inner condition, try running below codesnippet,

const queryFormat = (payload) => {
    let query = [];
    // LOOP OBJECT
    for(let key in payload) {
       // IS ARRAY? YES
       if(!Array.isArray(payload[key])) {
          query.push({ [key]: payload[key] });
       }
       // NO 
       else {
          let subQuery = [];
          // LOOP ARRAY
          for(let skey in payload[key]) {
            // LOOP OBJECT
            for(let okey in payload[key][skey]) {
              subQuery.push({ [okey]: payload[key][skey][okey] });
            }
          }
          // BIND SUB QUERY
          query.push({ [key]: { "$in": subQuery } });
       }
    }
    // RETURN MATCH QUERY
    return { '$match': query }
}

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

let result = queryFormat(payload);
console.log(result);

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!