How can I add both the keys and values to an array in order to construct a dynamic query?

When building the query object for MongoDB, I encountered an issue with the output. Here is what I got:

output

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

Here is 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}]} }]}}

Thank you!

Answer №1

To properly check if the key is an array or not, you can use a loop to create a new array for inner conditions. Try executing the code snippet below:

const checkArray = (data) => {
    let newArray = [];
    
    for(let item in data) {
        
        if(!Array.isArray(data[item])) {
            newArray.push({ [item]: data[item] });
        } else {
            let subArray = [];
            
            for(let subItem in data[item]) {
                for(let objKey in data[item][subItem]) {
                    subArray.push({ [objKey]: data[item][subItem][objKey] });
                }
            }
            
            newArray.push({ [item]: { "$in": subArray } });
        }
    }
    
    return { '$validate': newArray }
}

const data = {
    id: 2,
    name: 'Betty',
    location: 'earth',
    values: [{name: 'v', age: 7}]
}

let output = checkArray(data);
console.log(output);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Exploring the Power of VueJS Classes and Conditions

Is it possible to add a Class based on a Child's Class Condition in the menu? For example: <ul :class="{ 'open' : ThereIsClassInChild }"> <li v-for="item in list" :class="{ 'active' : $route.name == item.routeName }" ...

Using Vuetify 3 to conditionally render v-icon inside a v-data-table

I am struggling to display a v-icon conditionally in a v-data-table within Vuetify 3, based on a value of either 1 or 0. In Vuetify 2, there were multiple easy ways to achieve this, but it's not rendering in the latest version. I want to show v-icons ...

Enhancing the appearance of a checkbox within a ReactJS setting

I'm having trouble customizing a checkbox in a ReactJS environment for IE11. I've tried various approaches, but nothing seems to work. Can anyone offer any advice? Here is the code snippet: CSS: .squared { input[type=checkbox] { bo ...

What is the proper way to enable the Google Analytics cookie only once another consent cookie has been set and is marked as "true"?

I am currently using React/Nextjs on my website along with the react-cookie-consent library. This setup generates a pop-up where users can agree to the cookie policy, and if they do, a CookieConsent with the value "true" is set. In addition to this, I wis ...

Is there something I'm overlooking when it comes to vue router transitions?

I am attempting to implement a smooth transition between my Vue components with the following code: <template> <div id="app"> <router-link to="/">Go to home</router-link> <router-link to="Register">Go to register< ...

Understanding of clustered json

I am working with a JSON structure that looks like this: { "2014": [ "2014-01", "2014-02", "2014-03", ... ], "2015": [ "2015-01", "2015-02", "2015-03", ... ] } My task is to convert this JSON into an HTML structure, either using Jquery ...

Protractor's modal dialogue displays numerous outcomes when accessing ng-repeater elements

Trying to click on an element located within a repeater has presented some challenges. The issue arises from the fact that it is a modal dialog and returns multiple elements for the repeater. Each page in our application functions as a modal dialog, leadin ...

JavaScript is not designed to run a second time

Currently, I have a script set up using $(document).ready(). It works perfectly upon initial loading. However, I also need this script to execute whenever the user changes an HTML select control. Ideally, upon page load, I want the filter and sort functio ...

modifying the IP address used while making a jQuery request

I am currently working on integrating a payment system, but unfortunately, I do not have a static IP address and my country is restricted. I am using my personal hosting with the whitelisted IP, however, it seems like the initial request to their servers ...

Executing a function within ng-repeat loop four times in AngularJs

In the code snippet below, a ul is populated with 21 phones using HTML: <li ng-repeat="phone in phones" ng-class="{'digestTest': countDigestOccurences(phone) }"> <p>{{phone.snippet}}</p> </li> The JavaScript method cou ...

Rearrange the provided string in a particular manner

Looking to transform a string like '12:13:45.123 UTC Sun Oct 17 2021' into 'Sun Oct 17 2021 12:13:45.123 UTC' without calling slice twice. Is there a more elegant and efficient way to achieve this? Currently using: str.slice(18)+&apo ...

What is the best way to keep a button visible at all times and active without needing to be clicked?

<v-card :style="{ textAlign: 'left' }" class="basic-card pa-6" :class="{ 'small-padding': !$vuetify.breakpoint.xl }" elevation="0" flat :height="windowHeight - 104 + 'px&ap ...

Selenium webdriver cannot find the element within the JavaScript code

await driver.findElement(By.id('closeBtn')).click(); or await driver.findElement(By.xpath('//*[@id="closeBtn"]')).click(); When attempting to use the above conditions for a pop-up, it does not work as expected. An error is ...

How can I annihilate the reveal effect in Foundation 6?

I've encountered a problem with initializing reveal in Foundation 6. Specifically, I'm attempting to create a new instance for #menu on medium and small screens and remove it on large screens. However, I'm running into issues removing the da ...

When using NodeJS and MongoDB together, a POST request may receive a 404 error code

Despite having all the routes set up correctly, I'm encountering a 404 error when trying to send a POST request. I've searched through numerous similar questions but haven't come across a solution that addresses my specific issue. Below is ...

OrbitControls in THREE.JS fail to function properly when a DOM Element is layered on top of the scene

I am attempting to position labels as elements with position:absolute; over a THREEJS scene. The issue arises when the mouse hovers over one of the labels (the red box in the example below), causing the events that trigger OrbitControls to be "halted" by t ...

When accessing a method exposed in Angular2 from an external application, the binding changes are lost

In my code, I have a method that is made public and accessible through the window object. This method interacts with a Component and updates a variable in the template. However, even after changing the value of the variable, the *ngIf() directive does not ...

Creating a React component with a reference using TypeScript

Let's discuss a scenario with a reference: someReference; The someReference is essentially a React component structured like this: class SomeComponent<IProps> { getData = () => {}; render() { ...some content } } Now, how c ...

Add characterizations to object utilizing cropper plugin

After obtaining image attributes from the cropper plugin, I am looking to include two additional values: var data = $img.cropper('getData'); //Object {x: 90, y: 60, width: 720, height: 480, rotate: 0…} image_identifier = $('.image_identi ...

Tracking locations in real time with the AR.js framework

Is it possible to utilize the AR.js web framework for creating an Augmented Reality web app that helps users navigate from their current location to a specific destination with coordinates (lat, long)? I am looking to have it compatible with Chrome/Safari ...