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

Exploring the Potential of Using ngIf-else Expressions in Angular 2

Here is a code snippet that I wrote: <tr *ngFor="let sample of data; let i = index" [attr.data-index]="i"> <ng-container *ngIf="sample.configuration_type == 1; then thenBlock; else elseBlock"></ng-container> <ng-template #t ...

Checking the authenticity of trello board API responses with Python unittest

My current task involves writing a unittest that interacts with the Trello board API to validate the presence of a specific card. Initially, I attempted to use the /1/boards/[board_id]/lists endpoint to retrieve data in the following format: [{'card ...

AngularJS does not recognize a dynamically created array when using ng-include with ng-repeat

Issue with ng-repeat Directive I have encountered a problem where the ng-repeat directive does not track the addition of a new array, specifically 'options'. This issue arises when the directive is used within a template displayed using ng-dialo ...

Utilizing @Material-UI Tabs for a Stylish Navigation Bar

As a newcomer to the coding realm, I find myself on a quest for an answer that has proven elusive. Despite scouring various sources, none of the solutions I've stumbled upon seem to work in my case. The issue at hand revolves around my desire to util ...

How can I transfer data from two queries to Jade using Node.js (Express.js)?

I have a database with two tables - one for storing user information and another for managing friendship connections: setting up a friend list in mysql My goal is to create a profile page using Jade, specifically profile.jade: - each user in users ...

What is the process of transforming the character u0421 into the letter "C"?

After making a post query to the server, I received JSON data that had an incorrect symbol: instead of "Correct," it showed up as "\u0421orrect". How can I properly encode this text? The function parse_json appeared to handle it like "РЎorrect"; T ...

Change the space character ' ' to '-' when a key is lifted

Hey, I need some help with a coding problem. I have two input fields and I want to automatically mirror the text from the first input into the second input field using a keyup jquery function. However, my current setup adds a space whenever I hit the spac ...

Is there a way for ASP.NET MVC to automatically notify when a record is edited or updated?

Having recently used the NotifyIcon class in a windows application, I found it to be quite useful. As someone who primarily works as a web developer, I am curious if there is something similar available for websites. The website that I am working on inclu ...

What is the best way to achieve varying margins when adding divs in CSS?

Encountering CSS margin issues when adding new divs. Desiring a large margin between the Create Div button and minimal margin between Example Text Here. The desired outcome Margin is too small between Create Div button and Example Text Here, but good bet ...

Assigning a value to a cell depending on a specific condition

Currently, I have a column connected to a field known as state. The possible values for this field are either S or L. My objective is to map these values as follows: S => Short, L => Long The binding is structured in the following way: $scope.gridOption ...

JavaScript : Retrieve attributes from a JSON object

Situation : I have a JSON object with multiple properties and need to send only selected properties as a JSON string to the server. Approach : To exclude certain properties from the JSON string, I utilized the Object.defineProperty() method to set enumera ...

An issue arises when attempting to utilize the 'push()' method to append a string to a JSON array

I am looking to append strings to my JSON file structure shown below: { "items": [] } To achieve this, I have the requirement of using the following code: var items = require("../../config/item.json"); The approach I am taking is ...

Incorporate personalized feedback into a datatable with server-side processing

Trying to implement server-side processing for a datatable loaded from an AJAX response using this specific example The server response being received is as follows: {"msg":null,"code":null,"status":null,"result":[{"aNumber":"3224193861","bNumber":"32159 ...

Working with JSON Arrays in Scala

Working with a jsArray (json Array) and utilizing the import play.api.libs.json._ library. [{”device”:”Samsung S8”,”android”:true}, {”device”:”iPhone 8”,”android”:false}, {”device”:”MacBook Air Pro”,”android”:false}, { ...

Repeatedly utilizing a drop-down menu

Can a <select> menu be written and utilized in multiple locations on a webpage? For instance: <select id="dm"> <option value="">Select Quantity</option> <option value="less ">50 - 60</option> <option value="me ...

Is there a way to refresh a table view while in a class?

When I click the update status button, I want to reload the table view on InquiryViewController. The update status button fetches JSON data containing the status of a message. The code snippet is as follows: -(BOOL)getMessageStatus : (NSMutableArray *)em ...

There was a dependency resolution error encountered when resolving the following: [email protected] 12:15:56 AM: npm ERR! Discovered: [email protected] . The Netlify deploy log is provided below for reference

5:27:42 PM: Installing npm packages using npm version 8.19.3 5:27:44 PM: npm ERR! code ERESOLVE 5:27:44 PM: npm ERR! ERESOLVE could not resolve 5:27:44 PM: npm ERR! 5:27:44 PM: npm ERR! While resolving: [email protected] 5:27:44 PM: npm ERR! Foun ...

Use jQuery to swap out two div classes within a table cell (TD) if they are

Although I'm making progress, I must confess that jQuery and CSS are not my strong suits. The objective: To create a dynamic div within a table data cell for a calendar feature. The content of the div varies based on the date range input. A filled d ...

Switch out the content when the button is clicked

Seeking a code snippet to enable clicking a button (Button labeled "Next") for replacing existing code on the page with new code. Current code below should be replaced, starting from the score counter section. Please excuse any messy code as I'm new a ...

Use include files to wrap content in a div tag

I have a webpage index.html with the following JavaScript scripts: <script type="text/javascript> $(document).ready(function() { $('a.link').click(function() {var url = $(this).attr('href'); $('#content'). ...