Generate a JSON object with multiple items using JavaScript

I need to create an object in this format:

var query = {"filters":{"type":"OR","filters":[
   {"type":"EQ","fieldName":"name", "value":"Point_1"},
   {"type":"EQ","fieldName":"name", "value":"Point_2"},
   {"type":"EQ","fieldName":"name", "value":"Point_3"}
]}};

Currently, the names of the points (Point_1, Point_2, Point_3) are stored in an array named points[]. I want to dynamically generate this object based on the array.

This is what I have tried:

var filt = {filters:[]};
for(var i in points){
  filt.filters.push({"type":"EQ","fieldName":"name","value":points[i]}); 
}
var query = {"filters":{"type":"OR","filters":filt}};

However, this approach is not working as expected.

Could someone please point out where I might be making a mistake?

Answer №1

When setting up your query structure, it is important to ensure that filters are in array format. This can be achieved by defining filters as an array and directly pushing objects to it.

var filters = [];
for(var i in points){
  filters.push({"type":"EQ","fieldName":"name","value":points[i]}); 
}
var query = {"filters":{"type":"OR","filters":filters}};

Answer №2

To target the desired object, you can nest it inside the filters property.

const locations = ['Location_1', 'Location_2', 'Location_3'],
    query = { filters: { type: "OR", filters: locations.map(function (loc) {
        return { type: "EQ", fieldName: "name", value: loc };
    }) } };

console.log(query);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Angular UI Bootstrap collapse directive fails to trigger expandDone() function

I am currently utilizing UI Bootstrap for Angular in one of my projects, and I have developed a directive that encapsulates the collapse functionality from UI Bootstrap. Here is how it looks: app.directive( 'arSection', ['$timeout', fu ...

Preventing Page Content Overflow in Semantic-ui SideNav

I am currently working on a webpage that includes a side navigation bar. I recently started using semantic-ui and its grid system, but I'm facing an issue where the content of the page flows under the side nav and gets hidden. I have tried various sol ...

Managing errors in Node.js when inserting data into MongoDB

Hello everyone, I'm currently working on handling errors in the user signup module using Express. However, I'm facing an issue where the errors are not being handled correctly. Here is my code: handler.post(async (req, res) => { let otp = M ...

Text in SVG file misaligned at the edge

After creating an SVG with a base64 background image and two text areas for top and bottom texts, I encountered an issue on Internet Explorer and Edge. The problem is that the bottom text is aligned to the left instead of the center, and its position is in ...

Issue with data entry: unable to enter the letter 'S' in search field

This bug has been a real challenge for me. It's strange, but I'm unable to type the letter "S" into the search input field. Oddly enough, the keyboard seems to be functioning properly. Please find the sandbox below for reference: https://codes ...

Troubleshooting in ReactJS and NodeJS: Understanding the "Pass --update-binary to reinstall or --build-from-source to recompile" error

After moving a ReactJS + NodeJS project from one computer to another, I attempted to install dependencies by running npm install in the terminal. However, I received the following response: > [email protected] install /Users/Joshua/Projects/practi ...

Determine the presence of a JSON object within a file using JavaScript

Currently, I am developing a mobile app using react-native and have been facing challenges implementing error checking. To store data retrieved from an API in JSON format, I am employing redux along with thunk. At times, the search results yield a JSON res ...

What is the best way to retrieve scope variables from multiple directives?

I am working on a directive that represents a person with changing location attributes. My goal is to access all the locations together and plot them on a map using the angular-leaflet-directive. I'm struggling to figure out how to access these variab ...

Iterate over the array and show the elements only when a click event occurs

I am trying to create a loop through an array (array) and display the elements one by one only after clicking a button (bt). However, when I run this code, it only shows the last element of the array (i.e. honda). Can someone please help me fix this issu ...

Troubleshooting MongoDB and Node.js: Issue with updating variables when inserting documents in a loop

As a newcomer to MongoDB, I'm facing a puzzling issue that has left me confused. In my dataset, I have an array of Employee objects structured like this: { "Name" : "Jack Jackson", "Title" : "Senior Derp Engineer", "Specialties" : [ "Kicki ...

"Steps for implementing a multiselect feature with checkboxes, including the ability to check all and uncheck all, in a React application

After creating a custom component for selecting multiple options and adding a check all feature, the challenge arises when needing an uncheck option. Solution? Implementing an uncheck all feature alongside the select all functionality, but how to modify th ...

What is the most effective method for manipulating and slicing a string based on character matching?

In this particular scenario, we are dealing with strings that follow this pattern: CP1_ctl05_RCBPAThursdayStartTimePicker_0_dateInput CP1_ctl05_RCBPAFridayStartTimePicker_3_dateInput CP1_ctl05_RCBPAMondayStartTimePicker_1_dateInput The goal is to extract ...

Pictures acting erratic following the implementation of two setTimeout functions

I encountered an issue while developing a pong game using html/css/javascript. Everything was going smoothly until I introduced a second setTimeout() function. Here is the snippet of my html code: <!DOCTYPE html> <html> <head> <scrip ...

The POST method in Node JS request-promises does not properly handle string inputs

When I am trying to establish a connection between my node.js module and another server, I utilize the 'request-promise' library. My implementation for posting data looks like this: rp.({ method: 'POST', headers:{ 'Conte ...

Convert a JSON array with a single element into a valid JavaScript object

Within my programming scripts, I frequently utilize PHP arrays with numeric keys. However, these keys are not necessarily sequential from 0 to n; they can be randomly chosen. Specifically, I am working on a script that organizes scheduled events at specifi ...

Exploring Next.js: Leveraging fetch to retrieve data in getServerSideProps and passing it to the client via query parameters

I'm utilizing a getServerSideProps function on the directory page. pages/catalog/index.js export async function getServerSideProps(ctx) { const response = await fetch( `http://someDomen.com/api/ipro/catalog?${ctx?.query?.page ? `page=${ctx.quer ...

Creating dynamic flags with specific parameters using Pentaho and JavaScript

I am looking to optimize my code by finding a better way to achieve this. I have a variable called "hour" and I need to create flags for each hour of the day like so: if (hour == 0) {flag12AM = 'yes'} else {flag12AM == 'no'} if (hour ...

What is the best way to verify the existence of an email address?

I'm currently using the jQuery validation plugin and everything is working fine, but I've hit a snag when it comes to checking email addresses. The issue is that the plugin returns either true or false based on whether the email exists or not. Ho ...

How can I work with numerous "Set-Cookie" fields in NextJS-getServerSideProps?

When working with getServerSideProps, I found a way to set multiple cookies on the client device. This is the code snippet that I used: https://i.stack.imgur.com/Kbv70.png ...

Discover the initial two instances of a specific element within a collection of javascript objects

Within my javascript arraylist, I am currently storing the following elements: list = [ {header: "header1", code: ""}, {label: "label1", price: 10}, {header: "header2", code: ""}, {header: "header3", code: ""}, {header: "header4", code: ""} ] My que ...