Using Nested Arrays to Create Search Filters with Query Parameters

Here is the data structure I am working with:

[
    {
        id: // the field to be search
            {
                eq: '1234'  // eq is the operand; 1234 is the keyword
            }
    },
    {
        description:
            {
                like: 'desc'
            }
    }
]

What would be the best way to convert this structure (using Ember.JS) into query parameters like this:

?filter[id][eq]=1234&filter[description][like]=desc

This specific format is required by the API for the filters to be processed correctly.

Answer №1

Perhaps this is the solution you've been seeking:

const filterOptions = [
    {
        id: 
            {
                eq: '1234'
            }
    },
    {
        description:
            {
                like: 'desc'
            }
    }
];

let result = '';

filterOptions.forEach(function (item) {
  result += 'filter';

  Object.keys(item).forEach(function (property) {
    result += '[' + property + ']';
  
    Object.keys(item[property]).forEach(function (subProperty) { 
      result += '[' + subProperty + ']=' + item[property][subProperty]; 
    });
  });
  
  result += '&';
});

result = result.substring(0, result.length - 1);

console.log(result);

An alternative approach is to iterate through the array and utilize Object.keys() along with the forEach function to access the property name and value.

Answer №2

The solution is quite straightforward. Given that the first and second elements are different, I can safely assume that this pattern will persist.

So, here is the solution:

const data = [
    {
        id:{
            eq: '1234'
        }
    },
    {
        description:{
            like: 'desc'
        }
    }
];

const [ first, second ] = data;

const queryParams = `?filter[id][eq]=${first['id']['eq']}&filter[description][like]=${second['description']['like']}`;
console.log(queryParams);

Executing this will result in:

?filter[id][eq]=1234&filter[description][like]=desc

Answer №3

In ES6 fashion.

const filters = [
    {
        id: 
            {
                eq: '1234'
            }
    },
    {
        description:
            {
                like: 'desc'
            }
    }
];


const apiUrl = '?' + filters.map(filter => {
  const majorKey = Object.keys(filter).pop();
  const minorKey = Object.keys(filter[majorKey]).pop();
  return `filter[${majorKey}][${minorKey}]=${filter[majorKey][minorKey]}`;
}).join('&');

console.log(apiUrl);
// output: ?filter[id][eq]=1234&filter[description][like]=desc

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

Warning: The current version of graceful-fs (3) is deprecated in npm

I encountered an issue while running npm install. I attempted to run the following command before updating: $npm install npm, and also updated graceful-fs. $ npm install -g graceful-fs <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...

Mastering the correct usage of Express middleware functions in routers

Displayed in this instance, are the csrfProtection and parseForm functions being utilized as parameters/callbacks within the GET and POST requests... var cookieParser = require('cookie-parser') var csrf = require('csurf') var bodyParse ...

Utilize React-Charts.js-2 with ChartJS to create a customized bar chart

When creating bar graphs based on monthly data, everything works fine expect for the fact that the order of the months is not maintained and it appears mixed up in each rendering. The API provides the following data: { { "_id": 2022, &qu ...

Organizing dates with Javascript

Is there a way to convert a string from this format : 2014-06-12T23:00:00 To another format using JavaScript, like so : 12/06/2014 23:00 ...

What is the best method for incorporating jQuery code into a separate file within a WordPress theme?

I'm fairly new to working with Javascript/jQuery, so please be patient with me. Currently, I'm in the process of creating a custom WordPress theme where I've been using jQuery to modify the main navigation menu generated in my header file ( ...

Exclude a specific tag from a div in JavaScript

I need help selecting the text within an alert in JavaScript, excluding the <a> tag... <div id="addCompaniesModal" > <div class="alertBox costumAlertBox" style="display:inline-block;"> <div class="alert alert-block alert- ...

Tips for getting a sticky table header and including a limited number of columns, each with checkboxes or input fields

Encountering issues while trying to implement functionality with a jQuery library. One specific problem is the inability to interact with checkboxes on sticky columns, as well as difficulties clicking and typing in text fields. I am utilizing the jQuery S ...

Personalizing the label of a select input using materialui

Working on customizing a select element using the "styled" method: const StyledSelect = styled(Select)` height: 2rem; color: #fff; border-color: #fff; & .${selectClasses.icon} { color: #fff; } & .${outlinedInputClasses.notchedOutl ...

The data being retrieved from the controller in AngularJS is not displaying as expected

Just started learning AngularJS. Currently following this MEAN Stack Intro: Build an end-to-end application Created a basic html file to test angularjs. index.html <html> <head> <meta charset="utf-8"> <title> ...

Javascript - Incorporate a hyperlink into my Flickr Api image query

I am struggling with incorporating a link around the image generated by this request due to my limited API knowledge. Below is the current function responsible for displaying the album images. To see a functional version, please refer to the provided fidd ...

The function view() is not displaying the CSS and JS files properly

Having trouble with loading the css and js on my view: This is how I set up the controller: return view('home.news') ->with("news", $news); And here's how the route is defined: Route::get('/news/{id}&apos ...

Error not identified in ajax function for form submission

For some reason, in IE8 specifically, the alert function is not firing and the ajax part of my code is not running when I try to submit a form. Even though I have included a return false, the form still gets submitted. Why is this issue only occurring in ...

Is it possible to use next.js to statically render dynamic pages without the data being available during the build process?

In the latest documentation for next.js, it states that dynamic routes can be managed by offering the route data to getStaticProps and getStaticPaths. Is there a way I can create dynamic routes without having to use getStaticProps() and getStaticPaths(), ...

Showing headings in the table vertically

I have a header1 and header2 with corresponding data1 and data2 that I want to display differently. h h e e a a d d e e r r 1 2 data1 data2 To enhance the presentation, I wish to add borders around the head ...

Utilizing express-session and passport to initiate a new session for each request

Currently working on developing an e-commerce platform, both front and back-end. Using express and passport for a basic login/register system. The issue I'm facing is that every time a page with a request is accessed, a new session is created and stor ...

Is it expected to conceal children who are 2 years old?

I came across the following HTML code snippet: <ul id="product_create-header" class="stepy-header"> <li id="product_create-head-0" class="stepy-active"> <div>Categoría</div><span>Categoría</span> </ ...

Unraveling the Mysteries of Linguistic Evolution

I am curious about how to retrieve data from a map. I have three buttons on a JSP page: Register, Update, and Delete. The JSP files I am working with are First.jsp and Second.jsp. I have included First.jsp within Second.jsp using aaa. The buttons are l ...

Switch back and forth between two tabs positioned vertically on a webpage without affecting any other elements of the page

I've been tasked with creating two toggle tabs/buttons in a single column on a website where visitors can switch between them without affecting the page's other elements. The goal is to emulate the style of the Personal and Business tabs found on ...

Tips for Adding or Deleting 2 Rows in a Table

When the basket icon on the right is clicked, I want to remove both the current <tr> and the yellow one as well. Check out this screenshot: This is the HTML code for the two rows that need to be deleted with a click: <tr> <t ...

Can you provide the name of the slideshow plugin used on the Wipro website?

Can anyone tell me the name of the image slide show featured on: http://www.wipro.com/index.htm? Also, does anyone know where I can find the script for free? I am looking to incorporate it into a page that is coded in php, html, css, and javascript. Than ...