Here is a method to transform the JSON object into a string as demonstrated below:

Presented below is a JSON object:

{
  "category": "music",
  "location": {
    "city": "Braga"
  },
  "date": {
    "start": {
      "$gte": "2017-05-01T18:30:00.000Z"
    },
    "end": {
      "$lt": "2017-05-12T18:30:00.000Z"
    }
  }
}

I am looking to construct a query string in the following format:

category=music | location.city = Braga | date.start.$gte = 2017-05-01T18:30:00.000Z | date.end.$lt = 2017-05-12T18:30:00.000Z

Any ideas on how I can accomplish this?

Here is my current approach.

 _.each(this.filter, (val: string, key: string) => {
      if (key && val) {
        filterArray.push(`${key}=${val}`);
      }
    });

Answer №1

One approach is to iterate through the keys of an object and construct a path to its corresponding value. These paths can then be joined together and combined with the values to create a final string.

function extractPathValuePairs(obj) {
    function traverse(object, path) {
        Object.keys(object).forEach(function (key) {
            if (object[key] && typeof object[key] === 'object') {
                traverse(object[key], path.concat(key));
                return;
            }
            result.push(path.concat(key).join('.') + ' = ' + object[key]);
        });
    }

    var result = [];
    traverse(obj, []);
    return result.join(' | ');
}

var exampleObject = { "category": "music", "location": { "city": "Braga" }, "date": { "start": { "$gte": "2017-05-01T18:30:00.000Z" }, "end": { "$lt": "2017-05-12T18:30:00.000Z" } } };

var outputString = extractPathValuePairs(exampleObject);

console.log(outputString);

Answer №2

Apologies for the delay, but here we go.

The function walk recursively traverses your JSON data and calls a callback function with a chain of keys and value as arguments.
Subsequently, the function convert leverages walk to convert JSON into your desired format:

var walk = function( data, iterator, stack ) {
    var key;

    stack = stack || [];

    for ( key in data ) {
        if ( typeof data[ key ] === 'string' ) {
            iterator( stack.concat( [ key ] ), data[ key ] );
        } else {
            walk( data[ key ], iterator, stack.concat( [ key ] ) );
        }
    }
};

var convert = function( data ) {
    var result = [];

    walk( data, function( keys, value ) {
        result.push( keys.join( '.' ) + ' = ' + value );
    } );

    return result.join( ' | ' );
};

var query_string = convert( /* input your JSON data here */ );

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

Is it possible to filter a single field for two different values in a relationMapping using Objection.js?

In an Objection.js model, I have a relation mapping where I need to set a filter on a field that can only have two possible values: null or 0. Here is an example of the relation I am using: static get relationMappings() { return { dipendenti: { ...

Steps to enable overflow: 'scroll' for components generated dynamically

When developing a React application, I encounter an issue with creating new components dynamically inside a container. The problem arises when the height of the container gets exceeded by the newly added items, and I aim to make the container scrollable in ...

Creating a navigational sidebar with dynamic responses using Angular 8

Currently, I am working on creating a responsive sidenav USING ANGULAR WITHOUT MATERIAL DESIGN. My goal is to achieve the same level of responsiveness that can be seen on https://angular.io. Within my project, I have created separate components for the top ...

Understanding the relationship between csv and json array formats, along with the process of converting them into a json array using Node.js

Greetings! I have been searching for quite some time and have not been able to find the desired result. I am unsure of what a CSV file would look like with the following JSON array: [ { email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email_ ...

hover over the picture with your cursor

Struggling with jquery and css, could use some assistance :) Check out my html code below: <html> <head> //myscripts <script> $(document).ready(function(){ $(".cover").hover(function(){ //the function i need to write } ...

Having issues with @ts-ignore in Typescript on a let variable that is not reassigned?

JOURNEY TO THE PROBLEM My current task involves destructuring a response obtained from an Apollo useLazyQuery, with the intention to modify one variable. In a non-Typescript environment, achieving this would be straightforward with just two lines of code: ...

Is it necessary to incorporate Babel into a project that involves developing a backend service using Node.js and a front-end component using the EJS view engine?

I find myself a little confused. Some say that if you are working on pure Node.js projects, there is no need to stress about this issue. However, for web development, it's important to be familiar with these tools. On the other hand, some recommend us ...

Can MongoDB perform a case-insensitive search on Keys/Fields using Typescript?

Is there a method to process or identify a field called "productionYear" in the database, regardless of capitalization for "productionyear"? In other words, is it possible to perform a case-insensitive search on both fields and values? ...

Utilizing ngFor to generate buttons that are disabled based on specific conditions

I need assistance with creating a dynamic list of buttons from an array using ngFor. While I have achieved this, my current issue lies in disabling the buttons once they exceed a certain "number" representing the user's level. Here is an example of w ...

What is the best way to apply various styles using the ng-style directive in different scenarios?

When working in Angular, I am attempting to apply different style attributes based on varying conditions. However, the typical conditional expression method is limited to just two conditions and is not providing the desired results. <div ng-style=" ...

Click the button to instantly scroll to a particular word with highlighting, and with another click, jump to the next occurrence

In order to achieve the objective, simply click on a button that will search for and scroll to a specific word while highlighting it. The same button can be clicked again to find the next occurrence, and so on. If you need an example of how this works, ch ...

"Make sure the last if statement is always the one being executed

I have been using angularjs to develop a mini quiz application. I created 4 if statements, but for some reason, the last condition is always executed even if no answers have been selected. Why does $scope.makeup consistently display You should have makeup ...

Stop the scrolling behavior from passing from one element to the window

I am facing an issue with a modal box window that contains an iframe. Inside the iframe, there is a scrollable div element. Whenever I try to scroll the inner div of the iframe and it reaches either the top or bottom limit, the browser window itself start ...

Having trouble accessing properties of an undefined object when trying to read 'credentials' in Firebase Auth within ReactJS

I need to verify the user's password again before allowing them to change it. Currently, my Firebase Auth setup is defined in Firebase.js and exported correctly //appConfig = ...(all the configurations here) const app = firebase.initializeApp(appConf ...

Incorporate Angular directives within a tailor-made directive

I just started using a fantastic autocomplete directive called Almighty-Autocomplete. However, I feel like it's missing some features. The basic structure of the directive is as follows: .directive('autocomplete', function () { var index ...

Executing the `process.nextTick` function throws an error, causing the message: "Headers cannot be set once they have been sent."

I'm attempting to retrieve data from MongoDB within a Node.js file. I am encountering the following error: /home/jay/node_project/user_data_manag/node_modules/mongodb/lib/utils.js:98 process.nextTick(function() { throw err; }); Error: Can't ...

Filtering function that works without specific knowledge of keys

I'm working on a JavaScript method to filter a list dynamically without knowing the specific key (s). I've made some progress, but I'm stuck and not sure how to proceed. The foreach loop I have isn't correct, but I used it for clarity. ...

Troubleshooting Angular2: SVG Disappearing Upon Page Reload with PathLocationStrategy

I encountered a strange problem with SVG while using Angular2's PathLocationStrategy. The SVG code in my HTML template looks like this: <svg class="bell__icon" viewBox="0 0 32 32"> <use xlink:href="#icon-notificationsmall"></use&g ...

Deconstructing Angular 2 Custom Pipes

As I delve deeper into learning Angular 2, my recent endeavor involves creating a custom pipe to filter results in my gallery by category. Unfortunately, the resources I've been referring to lack detailed explanations on how custom pipes actually work ...

The Google Apps spreadsheet script occasionally fails to complete iteration but functions properly in all other aspects

I have a script that goes through a spreadsheet of student data one row at a time to email students and their parents if the student's grade is below 60. The spreadsheet columns include: Student ID, Name, Email Address, Parent's Email Address, an ...