Adding a JSON object to an API call: step-by-step guide

I have a variety of Objects stored in an array that are generated dynamically. My goal is to save each Object separately by sending it through an API. The challenge lies in the fact that there can be numerous Objects in the array. What would be the most efficient way to iterate over the array, extract the attribute name and its corresponding value, and make an API call for each object?

Essentially, only one Object will be saved at a time through the API. For example:

{
        "attributeName": "s1",
        "attributeValues": [
          "a",
          "b"
        ]
      }

The structure of my JSON Object is as follows:

[
  {
    "attributeName": "s1",
    "attributeValues": [
      "a",
      "b"
    ]
  },
  {
    "attributeName": "s2",
    "attributeValues": [
      "c",
      "d"
    ]
  },
  ...
]

I need to extract the attribute name and value from each Object and send it to the API individually.

Alternatively, if I were to save the entire JSON to the API, how could I later filter out and access individual Objects without prior knowledge of their attribute names? What other methods exist for obtaining a list of attribute names from the JSON data?

Answer №1

If you require JSON in the specific format below

[
  {'s1':['a','b']},
  {'s2':['c','d']},
  {'d1':['p','q']},
  {'d2':['r','s']},
  {'':['']},
  {'d2':['r','s']}
]

You have the option to make API calls for each child individually or send the entire array.

var arr = [
  {
    "attributeName": "s1",
    "attributeValues": [
      "a",
      "b"
    ]
  },
  {
    "attributeName": "s2",
    "attributeValues": [
      "c",
      "d"
    ]
  },
  {
    "attributeName": "d1",
    "attributeValues": [
      "p",
      "q"
    ]
  },
  {
    "attributeName": "d2",
    "attributeValues": [
      "r",
      "s"
    ]
  },
  {
    "attributeName": "",
    "attributeValues": [
      ""
    ]
  },
  {
    "attributeName": "d2",
    "attributeValues": [
      "r",
      "s"
    ]
  }
];

var obj = arr.map((o1) => {
  var o = {};
  o[o1.attributeName] = o1.attributeValues;
  return o;
});

console.log(JSON.stringify(obj));

Answer №2

Examine the data frequency. If FrontEnd is overloaded with too much data, it's recommended to send it in chunks. Alternatively, you can accumulate the data on FrontEnd and then proceed with sending.

async function sendAllData(data) {
  let results = [];
  for (let index = 0; index < data.length; index++) {
    const result = await axios.post('url', data[index].attributeValues);
    results.push(result);
  }
}

Example utilizing a fake mock api.

// function* dataLake(data) {
//   for (let item of data) yield item;
// }
const getFakeData = data => {
  return new Promise(r => {
    setTimeout(() => {
      r(data);
    }, 100);
  });
};

async function sendAllData(data) {
  let results = [];
  for (let index = 0; index < data.length; index++) {
    const result = await getFakeData(data[index].attributeValues);
    results.push(result);
  }
  return results;
}

const data = [
  {
    attributeName: "s1",
    attributeValues: ["a", "b"]
  },
  {
    attributeName: "s2",
    attributeValues: ["c", "d"]
  },
  {
    attributeName: "d1",
    attributeValues: ["p", "q"]
  },
  {
    attributeName: "d2",
    attributeValues: ["r", "s"]
  },
  {
    attributeName: "",
    attributeValues: [""]
  },
  {
    attributeName: "d2",
    attributeValues: ["r", "s"]
  }
];
sendAllData(data).then(console.log)

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

Error encountered: Null pointer exception while utilizing asyncTask

Recently delving into Android programming, I have been working on an app that connects to a PHP server file to retrieve JSON data. The app is in its final stages of development. It successfully fetches the JSON data from the server file and displays text b ...

Performing an AJAX request to the database when a change occurs, prior to submitting the

In my user setup/create form, I am including a field for the users' license/certification number which needs to be validated and returned to a specific DIV Onchange before the form is submitted. I have heard that using AJAX POST is the way to achieve ...

Ways to enforce a specific type based on the provided parameter

Scenario Background: // Code snippet to do validation - not the main focus. type Validate<N, S> = [S] extends [N] ? N : never; // Note that by uncommenting below line, a circular constraint will be introduced when used in validateName(). // type Val ...

Steer Your Way: How to Redirect to a Different Router or Middleware in Node.js and Express.js

I'm creating an application using VENoM stack, and I have set up some middleware in the API like this: const express = require('express'); const router = express.Router(); require('./routes/orderRoutes')(router); require('./ ...

Search form with a variety of fields that allows for searching without needing to repeat the component for each condition

I am currently facing an issue with my form that consists of multiple fields, each used to search through an API and display matching data in a table below. While I have successfully implemented this for one field, I now need it to work for all fields with ...

The footer is not extending all the way to the bottom when using a flex layout

While working on my website, I attempted to create a sticky footer. To achieve this, I used JavaScript to dynamically generate the <footer> element in order to keep it at the bottom of the page at different screen widths. My goal was to append the f ...

Console unable to display extensive JSON data

Using node.js, I have created a module that retrieves data from a SQL server database in JSON format. Below is the code: b.js var mssql = require('mssql'); var config = { user: 'sa', password: 'scott', server: & ...

Ways to select a single checkbox when other checkboxes are selected in JavaScript

var select_all = document.getElementById("select_all"); //reference to select all checkbox var checkboxes = document.getElementsByName("testc"); //retrieving checkbox items //function to select all checkboxes select_all.addEventListener("change", function ...

The invocation of Ajax with jQuery is considered unauthorized

I have spent the past 2-4 hours searching on Stack Overflow, but unfortunately, I haven't been able to find a solution to my problem. The issue I'm facing is that my code is supposed to alert the data value, but instead, it's only returning ...

An issue occurred when fetching data from MySQL using the HttpClient module in Angular 5

Facing an issue with my data fetching service, I'm encountering the following error: ERROR TypeError: this.http.get(...).map is not a function https://i.sstatic.net/k07QM.png Incorporating the HttpClient Module in my project. Here's the scri ...

Avoiding the opening of a select menu

Is there a way to prevent the dropdown menu from appearing when a select element is clicked in a form? I have attempted two methods but they did not work: $('select').click (function (e) { console.log (e); return false; }); and $(&apo ...

Exploring the depths of time travel in Redux without the aid of developer

Has anyone successfully achieved time traveling capabilities with Redux core? It seems that this feature is limited to the devtools and not advised for production use. I had planned on implementing Redux in a multiplayer game to assist with managing clie ...

Is there a way to delete a table's row using JavaScript?

Hey there, total newbie to coding here. I'm working on a simple to do list project. The adding function is working great, and here's the code for it: let salvar = document.getElementById("salvar") let remove = document.getElementById("remove ...

Create a panoramic view using six images using Three.js and WebGL

After successfully building a panorama with three.js using the CSS3D renderer, I am now looking to achieve the same result using the WebGL renderer. When working with CSS3D, I utilized the following code to create a seamless panorama: var sides = [ { url ...

The number of subscribers grows every time $rootscope.$on is used

I currently have an Angular controller that is quite simple: angular.controller('appCtrl', function ($scope, $rootScope) { $rootscope.$on('channel.message', function () { // do something here } }); In addition, I have a ...

How to choose `optgroup` in Vue 1.x

In previous iterations of vue.js, developers had the ability to generate a dynamic select list utilizing optgroups similar to the example found here. In the latest versions of vue, the documentation suggests using v-for within the options instead of optgr ...

What is the best way to alter a specific value within an object without losing other important data?

I'm currently working on developing a function that will activate when the count either matches or is half the initial price required to open, and it should not reset to false even if the count drops back to 0. Below is some sample data: openData = { ...

Leveraging the typeof Operator within a Class

How can we utilize typeof in order to specify the type of a class property? Take a look at both examples below, where example A works but example B does not. A) Works outside class const data: {age:number, name:string} = {age:10, name:'John'}; c ...

The Art of Angular Architecture: Transmitting Information from Parent to Child

Exploring the concept of templates within a template in the example below... @Component({ selector: 'component-a', template: `<div> <component-b></component-b> </div>` }) Should component-b share a s ...

Using the jasmine framework to create conditional test cases

Currently, I am working on Jasmine and my goal is to ensure that the test cases run only when the site's response status is okay (200). If the site fails to load, I do not want the test cases to execute. To achieve this, I am checking the site's ...