Using JSON.stringify to format data and making an asynchronous $http request

I am working with a JavaScript string that looks like this:

user_fav = "21,16";

I need to process this string through a function so that it becomes a JSON array with an id key, like this:

{"id":21},{"id":16}

This JSON array is then used in an $http request:

return $http({
    method: 'GET',
    url: getUrl('products'),
    params: {
        pageSize: 2000,
        pageNumber: 1,
        "filter": { "q": { "$or": [{"id":21},{"id":16}] } }, // <-- HERE
        sort: []
    }
});

When I send the original string user_fav in the $http request, everything works fine. However, when I convert the string into JSON using the converter below and send it in the $http request, it causes an error:

user_fav = "21,16";

var user_fav_to_array = "";
var splitFav = user_fav.split(",");

for (var i = 0; i < splitFav.length; i++) {
    user_fav_to_array += JSON.stringify({ id: parseInt(splitFav[i]) }) + ',';
}

var JSONFavs = user_fav_to_array.substring(0, user_fav_to_array.length - 1);

//Result: JSONFavs => {"id":21},{"id":16}

The error occurs in this part of the code:

return $http({
    method: 'GET',
    url: getUrl('products'),
    params: {
        pageSize: 2000,
        pageNumber: 1,
        "filter": { "q": { "$or": [JSONFavs] } }, // <-- HERE
        sort: []
    }
});

The error message is 417 (Critical Exception), and it is generated by the Backand.com system.

Answer №1

Take a look at the following code snippet. The code currently assigns a Json STRING to the $or property, but what is actually needed is an array of items. If you have any questions, feel free to ask!

user_fav = "21,16";
// Not necessary
//var user_fav_to_array = "";
// Create a new variable to store array items
var arrayData = [];
var splitFav = user_fav.split(",");

for (var i = 0; i < splitFav.length; i++) {
   // Unnecessary
  //user_fav_to_array += JSON.stringify({ id: parseInt(splitFav[i]) }) + ',';
  // Simply create a basic javascript object with an id and add it to the array at index i 
  arrayData[i] = { id: parseInt(splitFav[i]) }; 
}

//var JSONFavs = user_fav_to_array.substring(0, user_fav_to_array.length - 1);

// Then, in the Http Request filter, it should look like this: "$or": arrayData
"filter": { "q": { "$or": arrayData } }

Answer №2

It's possible that the issue lies with the variable declaration - var user_fav_to_array = "";
Consider updating it to var user_fav_to_array = [];

The presence of quotes may be influencing the behavior of your variable in an unintended manner. Unless strings are being interpreted as arrays in JavaScript.

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

Securely store files by encrypting them with Node.js before saving to the disk

At the moment, I am making use of the multer library to store files on the File system. This particular application is built using Node and Express. I currently have a process in place where I save the file on the server first and then encrypt it. After e ...

Avoid Sitecore Page Editor Errors by Saving Returns

I encountered an error when trying to save a page in the page editor. Interestingly, when I edit the page from presentation > detail and then display it in the page editor, everything works fine. Below are the details of the error logs: ERROR After par ...

Common issues encountered when using the app.get() function in Node.js

I've been attempting to develop a website that utilizes mongojs. I've implemented the code snippet below, but when I launch the site, it never reaches the app.get() section, resulting in a 500 error on the site. How can I ensure it responds to th ...

Unlocking the potential of the Bootstrap search dropdown

Currently, I am utilizing the following code to create a searchable dropdown menu. I found helpful guidance in this forum post. I am seeking advice on how to retrieve the value of the selected option. For example, if 'China' is chosen, I would l ...

How can I modify the color of a div when a validation error occurs?

I have recently completed a contact form with validation using the constraint validation api. Although the files are functioning as intended, I am curious if there is a method to make the error boxes turn red when an error occurs and white (or hidden) when ...

AngularJS - Organize Item Hierarchy with Separate Containers for Each Group

My goal is to incorporate a $scope variable within an AngularJS controller that has the following structure: $scope.hierarchy = { name: 'bob', selected: true, children: [ { name: 'frank' }, { name: 'spike' ...

Node.js: Retaining JSON objects with the highest value from duplicate entries

From an external source, I have imported JSON data containing various objects, some of which share the same ID value. For instance: { "ID": "1", "name": "Bob", "ink": "100" }, { "ID":&qu ...

Display data from two arrays in real-time

The following data is available: "PensionPlanSummary": [ { "Type": "DefinedContributionPension", "Participants": [ { "Year": 2018, "Value": 425.0 } ...

Why does the combination of "minus, space, minus" result in the "plus" operation?

When running the command 'node -e 'console.log(- -1)' it outputs 1, which is expected. However: When executing the command 'node -e 'console.log(1 - - 1)' it displays 2, which puzzles me. It seems like when subtracting a ne ...

Navigating through JSON in Angular

I am facing an issue with looping through my JSON data to extract the data output. While I can successfully loop through {GET_PUT_AWAY_Inspection_F:{.....}}, attempting (this.myData.GET_PUT_AWAY_Inspection.data) results in an error stating it is undefined. ...

The React Modal component seems to be malfunctioning within the context of Nextjs

Out of the blue, this issue popped up and I'm puzzled about why it's happening. I have two modals (with different names) that are identical in structure but only one is functioning properly. Both modals use the React-Modal library. The first moda ...

Tips for using jQuery to slowly change a CSS property to "auto"

I've encountered a situation where I have an element styled with position:fixed, and bottom: auto;. When I apply the command .animate({bottom : '10%'});, it smoothly slides to the specified position. However, when I try to set it back to its ...

outputting javascript within php

I'm struggling to extract the data returned by AJAX after a successful call. Instead of just getting the words printed by my JavaScript code, I end up with the entire script that is echoed in the PHP file. What I really need are only the words outputt ...

Incorporating Jackson JAXB annotations for root element inheritance mapping

Exploring the Jaxb annotated class hierarchy that includes inheritance at the document root element: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ParentClass", propOrder = { "parentField" }) public class ParentClass{ @XmlElement(name ...

Customizing the formatting of Angular's ui-select2 NoMatches message within a directive

I have a multiple select in a directive template and I want to customize the message that appears when no matches are found. The documentation on suggests overriding the formatNoMatches method for this purpose. This is the select element in my directive& ...

Struggling to integrate buttons into an h2 element with the use of createElement() and appendChild() in HTML/CSS/JS

As I work on developing a website, one of the features I've been implementing is the ability for users to add books to a list and then review or delete them. The process was smooth sailing until I reached the point of adding buttons for these actions. ...

Querying data in JSON using LINQ's dynamic method

Method with a variable that can accept various JSON structures to be queried over LINQ... Currently, my result is moving in the right direction by returning the selected results over the LINQ query but it's statically coded. I have multiple sets of ...

Setting the base path for a statically exported NextJS app

I am in the process of developing and deploying a React / NextJS application to a Weblogic J2EE server with a specific context. While I have some experience with React, I am relatively new to NextJS. The current steps for building and verifying the app ar ...

Creating a Python-based web application to handle JSON data processing

My task is to develop a Pythonic web service that will ultimately provide an HTTPS endpoint to process and exchange JSON objects with another web service via POST requests. In order to receive post requests from other services, what specific information d ...

Combining data from an object within an array in JavaScript

I am looking for a way to incorporate values from an Object (weekdayMap) into an existing array (vehicleAvailabilities) that contains objects. I require the value Montag on day one and Dienstag on day two. This pattern continues for each day of the week. ...