Storing JSON data in an array using JavaScript is a powerful method to

Here is an example of JSON data:

[{
    "address": "A-D-1",
    "batch": [{
        "batch_number": "B-123",
        "cost": [{
            "cost": "C1"
        }]
    }]
},
{
    "address": "A-85-1",
    "batch": [{
        "batch_number": "B-6562",
        "cost": [{
            "cost": "C16464"
        }]
    }]
},
{
    "address": "A-522-1",
    "batch": [{
        "batch_number": "B-4511",
        "cost": [{
            "cost": "C8745"
        }]
    }]
}]

I am looking to convert this JSON data into an array.

let data = JSON.parse('[{"address":"A-D-1","batch":[{"batch_number":"B-123","cost":[{"cost":"C1"}]}]},{"address":"A-85-1","batch":[{"batch_number":"B-6562","cost":[{"cost":"C16464"}]}]},{"address":"A-522-1","batch":[{"batch_number":"B-4511","cost":[{"cost":"C8745"}]}]}]');

for (let i = 0; i < data.length; i++) {

if (data[i].batch !== undefined && data[i].batch !== null && data[i].batch.length !== undefined && data[i].batch.length > 0) {
  let batchLength = data[i].batch.length

  let newObject = {}
  let newArray = []

  for (let j = 0; j < batchLength; j++) {
    if (data[i].batch !== undefined && data[i].batch[j].cost !== null && data[i].batch[j].cost.length !== undefined && data[i].batch[j].cost.length > 0) {
      let costLength = data[i].batch[j].cost.length
      for (let k = 0; k < costLength; k++) {

        newObject.location = data[i].address
        newObject.batch.number = data[i].batch[j].batch_number ? data[i].batch[j].batch_number : ''

        newObject.cogs = data[i].batch[j].cost[k].cost ? data[i].batch[j].cost[k].cost : ''
        newArray.push(newObject)
      }
    }
  }
}

}

The JSON data has been stored in the data variable.

I have attempted to use the code above, but I keep getting the last index repeated.

Desired Output:

[
   {
      "address":"A-D-1",
      "batch":{
         "batch_number":"B-123"
      },
      "cost":"C1"
   },
   {
      "address":"A-85-1",
      "batch":{
         "batch_number":"B-6562"
      },
      "cost":"C16464"
   },
   {
      "address":"A-522-1",
      "batch":{
         "batch_number":"B-4511"
      },
      "cost":"C8745"
   }
]

Any assistance would be appreciated.

Thank You.

Answer №1

Is this the kind of thing you're looking for?

const exampleArray = [{
  "location": "L-1",
  "group": [{
    "group_number": "G-12345",
    "price": [{
      "price": "$10"
    }]
  }]
}, {
  "location": "L-2",
  "group": [{
    "group_number": "G-54321",
    "price": [{
      "price": "$15"
    }]
  }]
}, {
  "location": "L-3",
  "group": [{
    "group_number": "G-98765",
    "price": [{
      "price": "$20"
    }]
  }]
}]

console.log(exampleArray.map(item => {
return {
location: item.location,
group_number: item.group && item.group[0].group_number,
price: item.group && item.group[0].price[0].price
}
}))

Answer №2

To obtain the information in array form, you can utilize the following method.

const jsonData = JSON.parse(someArray);
console.log(jsonData[0].address);

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

Unity troubleshooting: Android issue - difficulty locating JSON file

After successfully creating a script in Unity that allowed me to read and write to a JSON file without any issues in the editor, I encountered a problem when trying to run the application on my Android device. The json file named "playerData.json" was stor ...

Having difficulty importing JSON data containing arrays into the Firebase Realtime Database

Typically, I create a duplicate of a Node by using the 'Export JSON' option in the 3 dots menu located at the top right corner. Afterwards, I navigate to another path and import the same JSON file. A few days ago, I was able to perform this tas ...

Clearing existing HTML content in the TR body

I've been struggling with a Jquery/Ajax call that updates cart details. Currently, I can't seem to clear the existing HTML content in the cart-body (tablebody) even though the ajax request adds all the items to the cart successfully. The code sni ...

Utilize dynamic function calls in JavaScript

I am trying to dynamically call a function from a string like "User.find". The goal is to call the find() function in the User object if it exists. This is what my attempt looks like: var User = {}; User.find = function(){ return 1; } var input ...

Extract data from input field and transfer to another page using ajax without needing to submit the form

My form includes an email input field: <input type="email" id="email" name="email"/> There is also a verify button: <span style="cursor:pointer"> <p id="verify">Verify</p> </span> Upon clicking the verify button, a new in ...

Ensure that parameters are validated correctly in the Next.JS application router using the searchParams method

When building the page, I need to properly validate params in the Next.JS app router using searchParams. My goal is to show a main image (coverImage) for each photo on the /gallery page. When a photo is clicked, I want to display more photos of the same k ...

Having trouble with setting up ENV variables while deploying the app on Heroku

I recently deployed my node.js app to Heroku, and I'm facing some issues with its functionality. The app loads fine, but when I try to sign in, it breaks down. It seems like the environment variables are not loading correctly, specifically the db vari ...

Utilize the nest function in D3 to organize flat data with a parent key into a hierarchical structure

I'm searching for an elegant and efficient solution to transform my input data into a hierarchical structure using d3.js nest operator. Here is an example of the input data: [ {id: 1, name: "Peter"}, {id: 2, name: "Paul", manager: 1}, {id: 3, name: " ...

Using Knex in ExpressJS to insert a list of entries into SQLite with unique field constraints

I'm currently facing an issue with inserting a list of exercises into an sqlite database. The app is built on express JS and I am utilizing sqlite3 and knex to handle interactions with the DB. My goal is to add a set of exercises into the table exerci ...

Exploring Several Images and Videos in Angular

I'm experiencing a challenge with displaying multiple images and videos in my Angular application. To differentiate between the two types of files, I use the "format" variable. Check out Stackblitz export class AppComponent { urls; format; on ...

Unable to display a Google map within a webview when viewing a local HTML file

I am currently working with a local HTML file called basicmap.html that includes the following code: <!DOCTYPE html> <html> <head> </head> <body> <div id="map"></div> <script> ...

Execute Jquery ajax only on the initial invocation

When I am using ajax post in jQuery to build a portion of a page, I am encountering an issue where it only runs once. Below is the code snippet I am working with: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery ...

Successfully resolving the API without encountering any response errors, even after sending a response

Once the data is successfully saved in the database and the image upload is completed, I am attempting to send res.json. However, I keep encountering the error message API resolved without sending a response for /api/auth/registeration, this may result in ...

The event listener for 'ended' is triggering multiple times

I am in the process of developing a music app, and my goal is to have the next song automatically play when the current one ends. However, I am facing an issue where the EventListener seems to be triggered multiple times in succession - first once, then tw ...

Bring in resources without specifying

Is there a way to directly import an image into a JSX tag in React without having to declare it at the top of the file using import img from './this/is/file.png'? I attempted to do so with <img src={import './this/is/file.png'} alt= ...

Using React with Axios to trigger several requests with a single action

Let's say a user selects a team from a dropdown menu, triggering a request to an API endpoint. const selectHomeTeamStat = evt => { const { value } = evt.target; getStats(leagueId, value, 'home'); }; In this hypothetical scen ...

The functionality for navigating the Angular uib-dropdown using the keyboard is currently experiencing issues

I am currently utilizing Angular Bootstrap 2.2.0 in conjunction with Angular 1.5. Despite enabling the keyboard-nav option, I am experiencing issues with keyboard navigation on UIB dropdowns. Below is the snippet of my code: <div class="btn-group" ...

let parsedObject = jQuery.parseJSON(response);

I'm working with a script that involves parsing JSON data received via AJAX. The script looks something like this: var obj = jQuery.parseJSON(response); The 'response' variable stores a JSON string with the following values: [ { ...

Avoid running another process before the current one finishes in jQuery

I have a situation where I am using $.ajax inside a for loop in jQuery. for(var i=0; i < 2; i++) { $.ajax({ url :"/models/getdata"+i, dataType:"json", success:function(data) { } }); } The issue is that before the success function for i=0 completes, ...

Tips for effectively overlaying one container on top of another in a responsive manner

There are a pair of containers. The main container functions as the parent, while the child container acts as a tag to categorize the content. The objective is to position the tag container at the top right corner of the main content container, slightly of ...