0

I have an empty object like this

let queryParams = {}

I want to add some objects conditionally to this:

if(status){
  //add this 
  adminapproval:req.body.approvalStatus
}

if(type){
  //add this
  $or: [
        Sequelize.where(Sequelize.fn('concat_ws', Sequelize.col('firstName'), ' ', Sequelize.col('lastName')), {
                  $like: '%' + keyword + '%'
                }),
    { email: { $like: '%' + keyword + '%' } },
    { company: { $like: '%' + keyword+ '%' } },
    { mobileNo: { $like: '%' + keyword+ '%' } },
    { city: { $like: '%' + keyword+ '%' } },
    { country: { $like: '%' + keyword+ '%' } }
]} 

If the two conditions are true the final object look like this:

{
  adminapproval:req.body.approvalStatus,  
  $or: [
    Sequelize.where(Sequelize.fn('concat_ws', Sequelize.col('firstName'), ' ', Sequelize.col('lastName')), {
      $like: '%' + keyword + '%'
    }),
      { email: { $like: '%' + keyword + '%' } },
      { company: { $like: '%' + keyword+ '%' } },
      { mobileNo: { $like: '%' + keyword+ '%' } },
      { city: { $like: '%' + keyword+ '%' } },
      { country: { $like: '%' + keyword+ '%' } }
  ]
}

My solution is to put this individual object into array and build the object in aloop but I think its a bad way. Is there any other way to do this?

1

2 Answers 2

1

If you want to add a new key value pair to an object you can simply do so by assigning value object.newkey as if the object already had that key.

let queryParams = {};
if(/*condition*/){
    queryParams.adminapproval=req.body.approvalStatus;
}
if(/*condition2*/){
    queryParams.key1=value1;
    queryParams.key2=value2;
}

Hope this is what you were looking for.

Sign up to request clarification or add additional context in comments.

Comments

0
let queryParams = {
    ...status && {
        adminapproval: req.body.approvalStatus,
    },
    ...type && {
        $or: [
            Sequelize.where(Sequelize.fn('concat_ws', Sequelize.col('firstName'), ' ', Sequelize.col('lastName')), { $like: '%' + keyword + '%' }),
            { email: { $like: '%' + keyword + '%' } },
            { company: { $like: '%' + keyword+ '%' } },
            { mobileNo: { $like: '%' + keyword+ '%' } },
            { city: { $like: '%' + keyword+ '%' } },
            { country: { $like: '%' + keyword+ '%' } }
        ]
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.