Traverse through the nested JSON array using a loop

Exploring a JSON object:

{
  "date_price": [
    {
      "date": "Jan 2000",
      "price": 1394.46
    },
    {
      "date": "Feb 2000",
      "price": 1366.42
    },
    {
      "date": "Mar 2000",
      "price": 1498.58
    },
    {
      "date": "Apr 2000",
      "price": 1452.43
    }
  ]
}

In order to iterate through and store each date-price pair in a simple array, you can use the following approach:

var transformation = [];

transformation.push({date: i, price: d})

The challenge arises because the JSON object contains objects inside an array, making it impossible to directly utilize the forEach() loop on it.

Answer №1

If you have already parsed the JSON into an object...

let obj = JSON.parse(json);

...iterate through the data using map.

Please note: instead of an array of objects (as mentioned in your question), based on your feedback you are looking for a nested array structure.

Using ES5:

const transformation = obj.date_price.map(function(el) {
  return [ el.date, el.price ];
});

Using ES6:

const transformation = obj.date_price.map(el => [ el.date, el.price ]);

OUTPUT

[
  ["Jan 2000", 1394.46],
  ["Feb 2000", 1366.42],
  ["Mar 2000", 1498.58],
  ["Apr 2000", 1452.43]
]

DEMO

Answer №2

EDIT: If you already have the JSON as an object, you can simply extract the date_price property from it. This will give you an array of the exact object types you need.

var result = jsonObject.date_price; // This is the array you are looking for.

Alternatively...

var result = jsonObject['date_price']; // This is the array you are looking for.

Previous response assumed a JSON string...

If you have a JSON string like this...

// Here is your JSON string
var text = '{ "date_price": [ { "date": "Jan 2000", "price": 1394.46 }, { "date": "Feb 2000", "price": 1366.42 }, { "date": "Mar 2000", "price": 1498.58 }, { "date": "Apr 2000", "price": 1452.43 } ] }';

// Convert it into an object
var obj = JSON.parse(text);

// Access the date_price property which is already an array
var result = obj.date_price;

// Output to demonstrate
console.log(result);
for (var i = 0; i < result.length; i++) {
    console.log(result[i]);
}

Answer №3

Easy solution utilizing JSON.parse along with Array.map methods:

let jsonStr = '{"date_price": [{ "date": "Jan 2000", "price": 1394.46 },{"date": "Feb 2000",      "price": 1366.42},{"date": "Mar 2000","price": 1498.58},{"date": "Apr 2000","price": 1452.43}]}',
    jsonObj = JSON.parse(jsonStr);

//let transformation = jsonObj["date_price"]; // to retrieve a nested array

let transformation = jsonObj["date_price"].map(function(v){ return v; }); // to simulate a test loop
    
document.write("<pre>"+ JSON.stringify(transformation, 0, 4) + "</pre>");

Answer №4

This is the perfect solution as it is already in the exact format required, all you need to do is remove the nesting.

var dataObj = {
  "date_price": [
    {
      "date": "Jan 2000",
      "price": 1394.46
    },
    {
      "date": "Feb 2000",
      "price": 1366.42
    },
    {
      "date": "Mar 2000",
      "price": 1498.58
    },
    {
      "date": "Apr 2000",
      "price": 1452.43
    }
  ]
};

var dataArray = dataObj['date_price'];

Follow these steps and you're good to go!

Answer №5

Here is an example code snippet that demonstrates how you could achieve this:

let data = {
 "date_price": [
{
  "date": "Jan 2021",
  "price": 2000
},
{
  "date": "Feb 2021",
  "price": 2100
},
{
  "date": "Mar 2021",
  "price": 2200
},
{
  "date": "Apr 2021",
  "price": 2300
}
]
}

let newArray = Object.values(data).map((value) => {
    return value;
});

https://example.com/code-example

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

Include the URL as a parameter in the query when utilizing Tesseract OCR

I have successfully implemented the tesseract ocr, but I am wondering if it is possible to run tesseract with a URL as a parameter. I want to achieve the following: localhost/test.html/?othersite.com/image/image2.jpg Here are some image URLs for demonst ...

Utilizing ng-bind-html to establish Angular bindings within the HTML code

My scenario involves hitting a specific route (#/abc) and then making a POST request to the server to render the HTML received as a response. Instead of embedding this logic directly into $routeProvider.when, I came up with my own solution. This is how I ...

URL for requesting JSON data using Zend Framework

Just getting started with ZF1 and I'm tackling the task of obtaining a JSON response for a specific id. I have successfully retrieved all values from a table using the code below. The question now is, how can I pass a parameter from the URL? public ...

Error: The specified schema for the model "superheroes" is missing and has not been registered. Please ensure the schema is properly defined and registered

After updating my server with nodemon, I encountered the following error: C:\Users\mikae\Desktop\Project\node-express-swig-mongo\node_modules\mongoose\lib\index.js:523 throw new mongoose.Error.MissingSchem ...

How to retrieve a value from PHP using Ajax?

I am struggling to implement ajax for adding a div to display an error message. Despite my efforts, I keep receiving null as the error message instead of the expected value. The occurrence of null is traced back to <?php echo json_encode($_SESSION[&ap ...

Pattern matching for ' ... '

I've been struggling to make a regular expression work properly: I need it to match anything that starts with __(' or __(" and ends with ') or ") I attempted using /__\(['"][^']*['"]\)/g and /__\([&apos ...

The Express API will only provide the initial key-value pair of an object in the response

I'm working on fetching nested data objects. Although I can successfully retrieve the object data in the console, I encounter an issue when attempting to access this data using return res.json(imageObject). Instead of retrieving all key-value pairs of ...

Delete the child element if it is present in an HTML document

removeConnection(event) { let parentElement = document.getElementById('RemoveElement'); let childElement = document.getElementById(event.target.id); parentElement.removeChild(childElement); } Whenever I try to remove the child ...

What is the process for customizing the color and thickness of the active tab inkBarStyle in React Material-UI?

Check out this inquiry: How can I change the color of the active tab in MUI? And for a potential solution, have a look at this response: The provided answer seems to be effective: <Tabs inkBarStyle={{background: 'blue'}}>... However, I a ...

How can I solve a tridiagonal matrix using Python code?

Currently, I am tackling an issue involving tridiagonal matrices. I referenced the tridiagonal matrix algorithm on Wikipedia in order to implement a solution. However, I have encountered a roadblock and my solution remains incomplete. Feeling confused and ...

Explore the full range of events available on the Angular UI-Calendar, the innovative directive designed for Arshaw FullCalendar

Utilizing external events with Angular ui-calendar: HTML: <div id='external-events'> <ul> <li class='fc-event'>Event 1</li> <li class='fc-event'>Event 2< ...

Having issues with the Carousel feature in Bootstrap 5.3.1 while using Angular version 15

I'm currently in the process of setting up a carousel on my homepage. It seems like everything is in place, but there's something missing. The initial image, text, and arrows all display properly, but they are non-functional. I have correctly imp ...

Tips for retrieving page source with selenium Remote Control

Looking to Develop a Basic Java Web Crawler. WebDriver driver = new HtmlUnitDriver(); driver.get("https://examplewebsite.com"); String pageSource=driver.getPageSource(); System.out.println(pageSource); The result is as follows: <!DOCTYPE html PUBLIC ...

JavaScript's square bracket notation is commonly used to access nested objects within an object

My goal is to accomplish the following: this.inputs[options.el.find('form').attr('class')] = {}; this.inputs[options.el.find('form').attr('class')][options.elements[x].selector] = false; Unfortunately, I'm fa ...

Creating two variables that share an identical name

Can variables with the same name set outside of a function be called within the function? var a = $(window).width(); // This is the variable I want to call if(!$.isFunction(p)){ var a = $(window).height(); // Not this one alert(a); } FIDDLE ...

What is the best way to change an array of strings into a single string in JavaScript?

I am working with a JavaScript array that contains strings arranged in a specific format: arrayOfString = ['a', 'b,c', 'd,e', 'f']; My goal is to transform this array into a new format like so: myString = ["a", "b ...

Arranging arrays of various types in typescript

I need help sorting parameters in my TypeScript model. Here is a snippet of my model: export class DataModel { ID: String point1: Point point2 : Point point3: Point AnotherPoint1: AnotherPoint[] AnotherPoint2: AnotherPoint[] AnotherPoi ...

Troubleshooting SQLite Query Problems in Flask

I'm currently developing an API using Flask, and I have implemented an HTTP DELETE method that is responsible for deleting records in SQLite based on the ID provided as a JSON input. In case the specified ID does not exist in the database, no error o ...

Adding Bootstrap to container-specific styling in SCSS

I am currently in the process of upgrading to the most recent version of reactstrap & Bootstrap. Previously, I had reactstrap in my package.json file and downloaded Bootstrap SCSS in my client/src/styles/bootstrap directory. Now, my updated package.json c ...

Changing the background color of the dropdown button in Vue Bootstrap: A step-by-step guide

I've been struggling to modify the background color of a dropdown button, but no method seems to work. I've attempted changing it by using ID, removing its class and applying a new one, and even using !important to override the styles, but the ba ...