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

Select component with nested checkboxes for multilevel dropdown

I am interested in developing nested dropdowns with checkboxes, similar to the example shown in this image: Image 1 Is there a way to achieve this functionality using React? I have not been able to find any specific library that allows for this implement ...

Deactivate click events in the container div

Here is the html code snippet that I am working with: <div class="parent" ng-click="ParentClick()"> . . . <div class="child" ng-click="ChildClick()"> Some Text </div> </div> When clicking on Som ...

Click on each item within the v-for loop to gather relevant information, and subsequently iterate through the collected data

Within a v-for loop, I have implemented a button that, when clicked, retrieves specific data. The objective is to display this data below or in place of the clicked button. <div v-for="(item, index) in items" :key="index"> <button @click="fetch ...

Determine the position and quantity of elements in jQuery by comparing their IDs with the current page or element

Looking to retrieve the n (zero based) position of an element by matching the page and element ID... Let's use an example (Assume the current page ID is 488); <ul id="work-grid"> <li id="item-486" class="work-item"><!--/content--& ...

What is the best way to incorporate an AppBar featuring a Back to Top button from Material UI for React into my application?

While exploring the Material UI documentation, I came across this interesting code snippet: import React from 'react'; import PropTypes from 'prop-types'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from &ap ...

Finding a problem in node.js

I have encountered a problem while creating a server game using node.js. I am seeking assistance to resolve this issue. Here is the specific problem: https://i.stack.imgur.com/FMlsL.png app.js: var express = require('express'); var app = expr ...

Encountering an issue in a Vue console where the $ref is returning null and prompting an error message

It's puzzling why I keep encountering a console error in Vue that says "cannot read null of a $ref". Despite having the correct HTML template and adding logic to the script tag as needed, I'm still facing this issue - Cannot read properties of nu ...

Error: The server selection process has encountered an unexpected issue

Embarking on my journey with MongoDB and the MERN stack, I turned to these tutorials for guidance: https://medium.com/@beaucarnes/learn-the-mern-stack-by-building-an-exercise-tracker-mern-tutorial-59c13c1237a1 https://www.youtube.com/watch?v=7CqJlxBYj-M ...

Issue with fullcalendar: difficulty displaying events using ajax after clicking 'previous' or 'next' button

I am currently working on creating a calendar using fullcalendar. To retrieve data for the month, I make an external ajax request. Here are the key variables I utilize to render the fullcalendar: eventsJsonArray - used to load all events for the month ...

Using JavaScript for Text Processing on Disk

Currently, I have a set of HTML files that require automated processing such as regex replacements and more complex actions like copying specific text blocks from one file to another. I am considering creating a series of scripts to handle this processing ...

Struggling with displaying Firebase data in React

I am facing an issue with rendering data fetched from Firebase onto the screen. The problem arises when I attempt to call the function that retrieves data from the database inside the componentDidMount() lifecycle method. Surprisingly, the function does no ...

Ordering and displaying data with AngularJS

Trying to maintain a constant gap of 5 between pagination elements, regardless of the total length. For instance, with $scope.itemsPerPage = 5 and total object length of 20, we should have 4 pages in pagination. However, if $scope.itemsPerPage = 2 and tota ...

"The AJAX response returned a status code of 200, however, the PHP script being executed on the XAMPP localhost did not provide

The HTML code initiates a localhost function called getNodes which returns JSON data that is verified by JSON lint. However, when the same function is invoked using AJAX from a JavaScript file, a 200 response code is received without any response data. I h ...

Only certain fields are returned by JQuery's form serialize() method

Encountering an issue with the serialize() function in jQuery when attempting to submit a serialized form via AJAX. Some of the field values are not being retained. Suspecting a problem with either my HTML structure or jQuery code: <div id="register" ...

What causes an "Internal Server Error" when attempting to use data for a database request with AJAX GET/POST in Laravel?

There's a unique issue that I'm struggling to resolve... Every time I drag and drop an event into the calendar, an Ajax Post Request is sent to my controller. The controller then inserts some data into the database with the event name received v ...

When a new VueJS project is created, it failed to automatically install the necessary basic HTML files and folders

Hey there, I am completely new to Vue.js. Just recently, I installed the Vue.js/CLI and created a brand new project using vue create test. This prompted me to choose from three options: > Default ([Vue 2] babel, eslint) Default (Vue 3 Preview) ([Vue 3 ...

Tips for retrieving the file name from the <input type="file" tag within a JSP page

I am looking to retrieve the file path from an HTML input type="file, which is selected by the user in the file dialog. <script> function OpenFileDialog(form) { var a = document.getElementById("inputfile").click(); SampleF ...

How to incorporate user-submitted form data into the existing state using React

I am currently working on a React project that involves a form input. The goal is for the user to input a number into the field, and then take that number and add it to another number in the application's state. For example, if this.state.data initia ...

When utilizing AJAX XMLHttpRequest, the concatenated response text from Symfony's StreamedResponse becomes apparent

Below is the code for a controller that returns Line 1 as soon as the endpoint is called and then two seconds later it returns Line 2. When accessing the URL directly at http://ajax.dev/app_dev.php/v2, everything works as expected. /** * @Method({"GET"}) ...

Why does the value become "Undefined" once it is passed to the controller function?

I am unsure why the console.log function returns "undefined". $scope.onSizeSelected = function(productId, sizeQtyPrice){ console.log('The selected size is: ' + sizeQtyPrice); $scope.updateSelectedProductBySizeSelected(productId ,sizeQtyPrice ...