Transform a JavaScript object into the appropriate REST query format using the Meteor.call() function

In my attempt to make an API call to a Wordpress REST API, I came across different ways of doing so. The console version of the call looks like this:

http://dev.thomastraum.com/wp-json/posts?type=tt_works&filter[work_categories]=all&filter[posts_per_page]=1

Using Meteor, a functional call appears as follows:

return Meteor.http.call("GET", Settings.wpdomain + "/wp-json/posts", {params: {'type':'tt_works','filter[work_categories]':'all','filter[posts_per_page]':'1'}});

My question now is, how can I correctly format JavaScript objects to be passed into the Meteor call? Initially, I thought they should be structured like this:

ArchiveQuery = {
type:'tt_works',
filter:{
    work_categories:'all',
    posts_per_page:1
}
};

However, when I pass it like this:

return Meteor.http.call("GET", Settings.wpdomain + "/wp-json/posts", {params:ArchiveQuery);

it only returns posts with the specific type and ignores the rest of the query. I attempted EJSON.stringify(ArchiveQuery), but it produced a different formatted query with curly braces {}.

Answer №1

Your query format may not be very common, but you can easily format your object yourself using the following code:

function generateQuery(query, prefix, object) {
  for (var key in object) {
    var prop = (prefix) ? prefix + '[' + key + ']' : key;
    if (typeof object[key] === 'object') {
      generateQuery(query, prop, object[key]);
    } else {
      query[prop] = '' + object[key];
    }
  }
  return query;
};

function objectToQueryString(object) {
  return generateQuery({}, null, object);
};

Check it out in action 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

What could be the reason for the lack of rendering in this imported React component using System.import?

I've been experimenting with dynamic code splitting using webpack 2 and react. As part of my testing, I decided to create a component that fetches code asynchronously: import React, { Component } from 'react' export class Async extends Com ...

Unable to establish communication with server. Facing issues in connecting AngularJS with NodeJS

I am currently working on establishing a communication process between my server and client to receive either a "success" or "failure" response. The server is being developed using node.js with the express framework, while the client is built using angular ...

Passing data from PHP to jQuery in a file upload script

I'm facing a problem that I can't seem to solve on my own. What I am trying to achieve is to upload a file to the server via PHP (upload.php), generate a new filename, and then pass that new filename to my webpage (upload.html). Within my uploa ...

Tips for enhancing a JSON array by including attributes through JavaScripts

I need help in dynamically constructing JSON using Javascript. { "Events": [{ "Name": "Code Change", "Enabled": "true", "Properties": [{ "Name": "url", "Value": "val" }] }], "Properti ...

Encountering a mongoose error when attempting to use the push()

var mongoose = require('mongoose'), Schema = mongoose.Schema, ObjectId = Schema.ObjectId; var SongSchema = new Schema({ name: {type: String, default: 'songname'}, link: {type: String, default: './data/train.mp3&a ...

Guide to uploading a file into a MongoDB database with the help of Mongoose

Currently, I am working on a database application using Node-Express and mongoose. My goal is to enable users to upload various file types such as photos or documents directly into the database. Despite searching extensively for information online, I hav ...

onpageshow event behaves as expected exclusively on webkit browsers (triggers function solely when visible on the screen)

I am inserting an HTML file using an object tag. The encompassing div of the object tag is hidden with a display:none property. However, I encounter an issue where the onpageshow event that I placed on the body tag of the HTML object behaves differently a ...

Is it possible to utilize Dictionaries (key, value) collections with JQuery?

Is jQuery capable of supporting a collection of Dictionaries which consists of keys and values? I am interested in organizing the following data into a structured format: [1, false] [2, true] [3, false] This structure should allow for adding, looking up ...

Is there a way to align Amazon native shopping ads in my code to the center?

Hey there, I've been trying to use Amazon's native shopping ads but I've run into an issue. It seems like they won't load properly when embedded into a Div. I've tried editing the ID in CSS to include properties like: #amazon-id-h ...

Converting an array object to a JSON string in IOS 8 with Swift 1.2 - step by step guide

Arrays of objects are like treasures to me var JewelList = Array<JewelModel>() class JewelModel : Beautiful { var GemType : String var GemColor : String var GemDateDisplay : String var GemDate : String override init( ...

Requesting Access-Control-Request-Headers using jQuery Ajax POST method

I am attempting to send an AJAX request to my server. Initially, I referenced a library (in the web) within a <script> tag in my HTML document and executed it using the following code: $.ajax({ url: api_url + "movie/create", type : "POST", con ...

Mastering the Art of Merging 3 Arrays

Greetings to the Community I have a question regarding my code. I am looking to merge three variables together. $result = mysqli_query($con, "SELECT disease,age,SUM(CASE WHEN gender = 'm' THEN 1 ELSE 0 END) AS `totalM`, SUM(CASE WHEN gender ...

Retrieving Scikit-Learn Pipeline Stages from JSON Data

Being a newcomer to Python and ML, I kindly ask for your patience. I'm endeavoring to automatically create scikit-learn pipeline steps based on parameters specified in a JSON file. These Parameters are: { "scaler": ["STAN", "MINMAX", "MAXABS", ...

Can the AJAX URL be loaded onto a new page?

https://i.stack.imgur.com/5l63v.pngPardon the poorly phrased question, but I need some guidance on a specific requirement regarding opening a URL in a new page. Currently, I have designed an AJAX URL and I'm wondering if it's possible to open thi ...

Combining Struts2 JSON Plugin and Hibernate

I am in the process of trying to generate a JSON object from a List of AcaClasses. Here is an example of an Action Class: public class StudentJSONAction extends ActionSupport{ //The result List private List<AcaClass> gridModel; publi ...

Tips for accessing field keys within a MongoDB document

Attached is a sample document: { 'id': 123, 'somekey': { 'x': [], 'y': [], 'z': [], } } How can I extract ['x', 'y', 'z'] from the docume ...

Properties of objects changing dynamically

<div id="bach">Bach</div> <div id="show">about composer</div> $(window).load(function(){ bach = {"bdate": 1685, "bplace": "Eisenach, Germany"} $("div").click(function(){ $("#show").text(this.id['bdate']); // ...

Transform JSON data into a single string by converting arrays with JOLT

Suppose my JSON input looks like this: { "rating": { "primary": { "value": [ "a", "B", 1] } } } My goal is to transform it into the following format: { "values": "a, B, 1& ...

`Can you teach me how to dynamically load HTML elements using input JSON data?`

What is the best way to iterate through an input array of objects? I currently have data for only 2 people included. However, there are more than 50 people's information in the input and I need to loop through all of them. Here is a sample code snip ...

Create the key's value in a dynamic manner within localforage

When utilizing localForage to store data offline, I encountered an issue with generating unique key values for each form submission. My goal is to have the key value generated dynamically as 'activity_1', 'activity_2', 'activity_3& ...