Generating a nested JSON object in Javascript can be achieved by using

Greetings, I am embarking on the task of creating a JSON Object to store resources in a post request using JavaScript. Let's consider an array of input disk sizes as an example:

For Request 1: input = [10, 20, 30]

"storageResources": [
  {
    "stats": [
      {
        "name": "diskSize",
        "units": "GB",
        "value": 10
      },
      {
        "name": "diskIopsConsumed",
        "value": 0
      },
      {
        "name": "diskConsumedFactor",
        "value": 1
      }
    ]
  },
  {
    "stats": [
      {
        "name": "diskSize",
        "units": "GB",
        "value": 20
      },
      {
        "name": "diskIopsConsumed",
        "value": 1
      },
      {
        "name": "diskConsumedFactor",
        "value": "NaN"
      }
    ]
  },
  {
    "stats": [
      {
        "name": "diskSize",
        "units": "GB",
        "value": 30
      },
      {
        "name": "diskIopsConsumed",
        "value": 0
      },
      {
        "name": "diskConsumedFactor",
        "value": 1
      }
    ]
  },
],

For Request 2: input = [10, 20]

"storageResources": [
  {
    "stats": [
      {
        "name": "diskSize",
        "units": "GB",
        "value": 10
      },
      {
        "name": "diskIopsConsumed",
        "value": 0
      },
      {
        "name": "diskConsumedFactor",
        "value": 1
      }
    ]
  },
  {
    "stats": [
      {
        "name": "diskSize",
        "units": "GB",
        "value": 20
      },
      {
        "name": "diskIopsConsumed",
        "value": 1
      },
      {
        "name": "diskConsumedFactor",
        "value": "NaN"
      }
    ]
  }
],

Should this be accomplished with a function or by sending it through properties? Share your thoughts!

Answer №1

Utilize Array.prototype.map to customize the output

$$text.oninput = evt => {
  let json = JSON.parse($$text.value)
  let result = json.storageResources.map(resource =>
    resource.stats.find(e => e.name == 'diskSize').value
  )
  
  console.log(result)
}

$$text.oninput()
<textarea id="$$text">{"storageResources":[{"stats":[{"name":"diskSize","units":"GB","value":10},{"name":"diskIopsConsumed","value":0},{"name":"diskConsumedFactor","value":1}]},{"stats":[{"name":"diskSize","units":"GB","value":20},{"name":"diskIopsConsumed","value":1},{"name":"diskConsumedFactor","value":"NaN"}]},{"stats":[{"name":"diskSize","units":"GB","value":30},{"name":"diskIopsConsumed","value":0},{"name":"diskConsumedFactor","value":1}]}]}</textarea>

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

Having difficulty retrieving form data with tag name using jQuery

Looking to retrieve form data using jQuery, I've experimented with two different approaches: var form = document.getElementById('user_form'); //Using form id var form = document.getElementsByTagName('form'); //Using form tag na ...

When using useEffect in React, the handleKeyDown function is causing the output to double with each

Whenever a user inputs something, the output doubles each time, leading to a long loop after just a few inputs. Below is the code snippet: const [direction,setDirection] = useState(Array(1).fill(0)); const directions = ["botNorth","botEa ...

Pass information from one .jsp file to a JavaScript function in another .jsp file

Here is the content of OneEmployee.jsp: <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <form> <td> <c:out value="${emp.getEmpid()}"/></td> <td> <input type="text" id="fname" value="<c:out v ...

Refreshing the HTML form upon submission

Looking to utilize Javascript for form submission? Check out the HTML below. <form onsubmit="post();"> //input fields here </form> Below is the Javascript code for the post() function. var post = function() { alert('the form was submitt ...

What is the process for integrating JavaScript Modules into an Angular-Cli application?

I recently added the open source library QuillJS as a standalone project to my Angular CLI app. Following the Quill Docs, I included Quill.js in my scripts to make use of the library. However, I encountered an error when running my Angular app with Quill. ...

Why isn't my custom wildcard search working properly in Marklogic using the Java API?

I am attempting to perform a wildcarded search in Marklogic using Java. Here is the current data structure in Marklogic: /articles/1.json 1.json: [{ "title":"hello%20world1", "content":"article content etc..." }] /articles/2.json 2.json: [{ "title ...

Is it possible for a React application to manage errors (status code 4xx) using a try-catch block

Currently delving into React (using hooks) and facing an interesting challenge. I am in the process of building a Notes Application (from FullStackOpen's learn react section). The database I'm working with only allows notes with content length gr ...

Tips for modifying the relative path in a CSS file using npm scripts

Currently, I am working with create-react-app and have encountered an issue after running npm run build. The build process generates a folder, within which there is a minified CSS file. My goal is to edit this file upon running npm run build. url(/static/ ...

Accessing the Next.js API after a hash symbol in the request URL

Is there a way to extract query strings from a GET request URL that contains the parameters after a '#' symbol (which is out of my control)? For example: http://...onnect/endpoint/#var_name=var_value... Even though request.url does not display a ...

Retrofit2 encountered a Reddit JSON response where it expected an array, but found an object instead

Apologies in advance for repeating the question, but I really want to gain a better understanding of how this process works. Despite my efforts, I have been unable to find a relevant answer regarding my JSON response. The JSON response I am attempting to ...

Extend an array by Parsing JSON

I'm struggling to retrieve the JSON string from localStorage and add a new dish to it. It's not functioning correctly, can anyone lend me a hand? I am utilizing TypeScript. interface Dish { id: number; name: string; desc: string; ...

Pull in class definitions from the index.js file within the node_modules directory

In my project, I have the package called "diagram-js" in the node_modules. The file node_modules/diagram-js/lib/model/index.js contains multiple class definitions as shown below: /** * @namespace djs.model */ /** * @memberOf djs.model */ /** * The b ...

Retrieving the value of a class property using JsonProperty

When it comes to environment configurations, we are saving JSON blobs in our database with the following structure: [ { "env": "local", "keya": "valueA_local" "keyb": "valueB_local" }, { "env": "development", "keya": "valueA_dev" ...

Using react-formik to implement responsive fields in a React application

I've been tasked with creating a dynamic form that pulls fields from a STRAPI api. The form will serve as a component to be reused on different pages, each displaying the same form but with varying fields based on the data returned by Strapi. Here i ...

executing a "background process" in javascript

Can JavaScript execute functions in the background? I am using the pdfmake tool to generate a PDF within an AngularJS application, but the generation process takes around 3-4 seconds and causes the UI to freeze completely. I want to run a background task ...

Node.js is not accurately setting the content length. How can I resolve this issue?

I could use some assistance. Even though I have set the content-length on the response object, it doesn't seem to be working. Have I done something incorrectly? res.set({ 'Content-Type': res._data.ContentType, 'Content-Length' ...

Tips for displaying a loading spinner during the rendering of a backbone view

I'm looking for some assistance in rendering a Backbone view that contains a large amount of information. Ideally, I would like to incorporate an animation (spinner) while the information is being rendered. Can anyone offer guidance or help with this ...

Creating JSON paths conditionally using jq: A comprehensive guide

I have a complex structure of JSON objects that are nested in various levels. { "category1": "value1"`, "category2": { "a": "value2", "b": "value3" }, "category3& ...

Why does the Google Tag Manager noscript tag show up as a string when using react-gtm-module?

Implementing Google Tag Manager Tags in a React/Next.js app hosted on Netlify, I used the react-gtm-module. While the gtm script tag in the head section works perfectly, the noscript tag in the body is displaying an iframe as a string: <body> < ...

Transitioning from embedded browser to system browser in a Next.js / React.JS application

I'm currently dealing with an issue on my Next.js payment page and could really use some expertise. Here's the situation at hand: My payment page has a QR code that directs users to the payment page created with Next.js. When users scan this QR ...