Extracting information from JSON structure

My JSON object response includes a `series` array of objects structured like this:

{
series: [
    {
    name: 'a',
    data: [1,2,3]
    },
    {
    name: 'b',
    data: [4,5,6]
    }
]
}

I am looking to extract the `data` values that correspond to specific `name` values.

Currently, I have achieved this:

$scope.nameArr[i] = response.series[i].name;

While this retrieves the correct `name` array, my attempt to retrieve corresponding data values with the following code fails:

for(var i=0; i<response.series.length; i++) {
    $scope.nameArr[i] = response.series[i].name;
       for (var j=0; j<response.series[i].data.length; j++){                                
             $scope.dataArr[j] = response.series[i].data[j];
       }
}

Answer №1

If you want to retrieve data by name, you have a couple of options. One way is to use array.filter, which can easily filter the data without the need for nested loops.

Personally, I find using the filter method easier to read, although the for-loop may be slightly faster in terms of execution time.

Feel free to check out the demo provided below or visit this fiddle link for more information.

var response = {
  series: [{
    name: 'a',
    data: [1, 2, 3]
  }, {
    name: 'b',
    data: [4, 5, 6]
  }]
};

function getDataByName(name) {
  return response.series.filter(function(item, index) {
    console.log(item);
    return (item.name == name);
  });
}

var filtered = getDataByName('a');
console.log(filtered[0].data);
$('#result').append('with filter: ' + JSON.stringify(filtered[0].data) + '<br/>');

var item, series = [];
var queryByName = 'a';

for (var i = 0; i < response.series.length; i++) {
  item = response.series[i];
  if (item.name == queryByName) {
    series.push(item);
  }
}

$('#result').append('with for loop: ' + JSON.stringify(series[0].data));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>

Answer №2

Here is a suggestion for you:

Iterate through the 'series' array using Angular's forEach method and push each item name to the $scope.nameArr and data to $scope.dataArr arrays.

Answer №3

If you're looking for a Javascript solution, consider adjusting your approach to the foreach loop by using:

angular.forEach(array, function(item)....etc

Take a look at this example:

var x = {
series: [
    {
    name: 'a',
    data: [1,2,3]
    },
    {
    name: 'b',
    data: [4,5,6]
    }
]
}

var results = [];
x.series.forEach(function(item) {
    item.data.forEach(function(subitem) {
    results.push(subitem);
  })
});

console.log(results)

Check out the code in action here: https://jsfiddle.net/6worooos/1/

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

How can you apply a class to a different element by hovering over one element?

Is there a way to darken the rest of the page when a user hovers over the menu bar on my website? I've been playing around with jQuery but can't seem to get it right. Any suggestions? I'm looking to add a class '.darken' to #conte ...

Unable to display JSON results in a tabular format

After successfully implementing the AJAX method in jQuery, I am able to receive a response. However, I am encountering difficulties when trying to display the arrays in a table format. success:function(resp){ var json =JSON.parse(JSON.stringif ...

"Effortlessly Engage Users with Rails and AJAX Comment Posting

Running a simple blog app dedicated to video game reviews, I encountered an issue with AJAX. As a self-taught student developer, I'm facing a challenge where posting comments on review pages triggers a full page refresh instead of dynamically updating ...

What is the best method for compressing and decompressing JSON data using PHP?

Just to clarify, I am not attempting to compress in PHP but rather on the client side, and then decompress in PHP. My goal is to compress a JSON array that includes 5 base64 images and some text before sending it to my PHP API. I have experimented with l ...

What is the technique to flatten a dataframe that originates from a nested JSON structure with arrays included?

New to coding Spark with Scala, I'm currently working on flattening a JSON into a dataframe for writing in Hadoop. Dealing with nested JSON containing arrays is proving to be a challenge. Any suggestions on how to flatten the JSON in a dataframe? Bel ...

Issue with unnamed column in Pandas dataframe prevents insertion into MySQL from JSON data

Currently, I am working with a large JSON file and attempting to dynamically push its data into a MySQL database. Due to the size of the JSON file, I am parsing it line by line in Python using the yield function, converting each line into small pandas Data ...

What is the reason for JavaScript consistently returning the initial value as the result?

My current issue involves customizing Joomla article content using a module. I am attempting to hide a div until a user clicks on an input, such as a radio button labeled Test1. Once Test1 is selected, another hidden field within the div should display the ...

Event fails to trigger when attached to different elements

Currently, I have an onchange event linked to the input text box and an onclick event attached to a text link. Interestingly, when I click on the link after editing the textbox, the click event does not trigger - instead, the change event is fired. If you ...

Can you link the source of an image to a local JSON file in Vue.js?

I currently have a local JSON file that contains an image. [{ "image": "/img/slider-first.jpg" }] I am importing this file into my component like so: const data = require('../assets/pets-data.json') Next, I'm trying to display the imag ...

AngularJS: Updated URL but no content displayed on the page

I have separate modules for my login page, which uses the loginApp module, and my home page, which utilizes the myApp module. Upon submitting on the login page, I aim to direct users to home.html. Within my index.html (login page), the script is as follow ...

What is the best way to retrieve a comprehensive outcome from a sql search utilizing php and consequently showcase it using javascript?

Need help with my PHP script that executes a query and returns multiple rows? Learn how to use json_encode in conjunction with JavaScript to fetch this data and display it in a table. This code snippet echoes two JSON encoded lines, each representing one ...

Map checkboxes aren't updating after an array update following a refactor to react hooks

I recently transformed a class component into a function component using hooks. However, I am facing an issue where the checkboxes within a specific mapping are not updating with the checked value. The onChange handler is firing and updating the array corr ...

Detecting if a user's location is inside a Geo-JSON polygon in Swift - is it possible?

How can I determine in which polygon a user's location falls, by OBJECTID, using Swift or Objective-C? The JSON data of the polygons I am working with is as follows: { "type": "Feature", "properties": { "OBJECTID&qu ...

Issue with Angular app occurring on one device, functioning properly on others - Error: $injector:unpr Unknown Provider

Whenever I try to run my application on my usual Windows machine, I keep encountering the following error: Error: $injector:unpr Unknown Provider Interestingly, the app works perfectly fine on other machines running Windows, MAC, and Linux. Since the we ...

What strategies can be implemented to decrease the initial loading duration of a YouTube iframe video?

What are some techniques we can use to decrease iframe loading time? Is it possible to implement lazy loading for YouTube iframe videos? I experimented with initially hiding the iframe and displaying an image instead. However, when the user clicks, it req ...

Exploring ways to retrieve the parent property name within System.Text.Json.Serialization.JsonConverter

Working with a 3rd Party API that provides data in the following format: { "dynamicFields": { "prop1": "val1", "prop2": "val2", "prop3": "val3" }, // otherFields ... } ...

NuxtJs login feature is functional, but encounters an unauthorized 401 error

I am utilizing the NuxtJs auth module to manage my authorization within the application state. I have created an express API specifically for this purpose, and it functions correctly. Below is the configuration included in my nuxt.config.js file: axios ...

Customizing the HTTP request error message in Spring Boot to display a custom message instead of the default 400

As I work on developing a Restful API with JSON responses, I have enabled Https by default for security reasons. However, whenever I attempt to access endpoints using the http protocol, I receive a 400 error message indicating: Bad Request This combinati ...

Fetching values from a JSON array in Java

In my Java code, I am working with a JSON array. Below is the structure of my JSON object: jsonString: {"user1": [ { "id":"11", "address":"Roshan shore", ...

Creating a button that redirects to an external link in CodeIgniter:

Hello everyone, I'm new here and I could really use some assistance with a problem. I am trying to link the button labeled 'lihat rincian' and each row of tables to redirect to an external link like Here's a snapshot of my datatables ...