Ways to retrieve JSON data using getRequest

Hey there, I have a string that looks like this:

{"Fruit":"Meat",
     "Vegetable":[
       {"Name":"Author1","Date":"12"},
       {"Name":"Author2","Date":"2"},
       {"Name":"Author3","Date":"14"}
       .
       .
       .
       {"Name": "AuthorN", "Date":"18"}
    ]
} 

This string is connected to a JSON/GetNames service.

Can anyone share a JavaScript function that can extract and return all the "Name" values nested under "Vegetable"?

Answer №1

Using the following code:

var jsonStr = '{"Fruit":"Meat","Vegetable":[{"Name":"Author1","Date":"12"},{"Name":"Author2","Date":"2"},{"Name":"Author3","Date":"14"}...{"Name": "AuthorN", "Date":"18"}]}';    
var object = JSON.parse(jsonStr),
    names = [];

for (var i = 0; i < object.Vegetable.length; i++) {
    var item = object.Vegetable[i],
        name = item.Name;
    names.push(name);
}
// Lastly, display the result:
console.log(names);

If you simply want to print the names instead (shorter version):

var object = JSON.parse(jsonStr);
for (var i = 0; i < object.Vegetable.length; i++)
    console.log(object.Vegetable[i].Name);

Cheers

Answer №2

Using a for loop is usually effective (after the data has been processed).

for (var i = 0; i < data.vegetable.length; i++) {
    console.log(data.vegetable[i].name);
}

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

Having issues with email verification and the length of phone numbers not functioning properly

I need to validate two text fields before registration: the email must be in correct format and the number must have exactly 11 digits. Any mismatches should trigger an error message. For the email validation, I used a function that checks for the require ...

How to handle redirection in React when encountering a 404 error with React

Hey there, I'm encountering an issue related to react router. Let's take a look at my App.js file where all the routes are defined: const App = () => ( <div className="App"> <MediaQuery minWidth={700}> {(matches ...

Struggling to set up an adapter within a fragment to display JSON data

I am facing an issue with displaying an array list using JSON in a fragment. The code works perfectly in an activity but not in a fragment. What I am trying to achieve is simply show a list of data using JSON, and when the user clicks on the code, the data ...

Utilizing ES6 imports with module names instead of paths

Is there a way to import modules using just their name without the full path? For instance, can I simply use: import ViewportChecker from 'viewport-checker'; instead of import ViewportChecker from '../ViewportChecker'; I'd ...

Guide to utilizing a directive for dynamic template modifications

I am facing a challenge with this specific instruction. angular.module('starter.directive', []) .directive('answer', ['Helper', function (Helper) { return { require: "logic", link: function ...

Retrieve information from table1 where the value of id1 is equal to the value of

I am seeking assistance with a script, example here There are three tables: networks network_id network_name status offers offer_id offer_name onetwork_id status list_ip network offer In the index page at IP Address Detai ...

Is Protractor compatible with Internet Explorer 9?

For my Angular App that is running on IE9, I need to create end-to-end acceptance tests. I'm curious to know if the browser simulated by Protractor matches the behavior of IE9 or a newer version? ...

Deletion of a custom function in JavaScript

I have written some basic code to generate and remove an image using functions. Specifically, I need help with removing the image created by the function Generate() when a button linked to the function Reset1() is clicked. Here's the code snippet for ...

Is there a way to organize a specific column based on user selection from a drop down menu on the client side?

When selecting Timestamp from the drop-down menu, I expect the TimeStamp to be sorted in either ascending or descending order. Similarly, if I choose Host, the Host should be sorted accordingly. Despite using the Tablesorter plugin, sorting doesn't s ...

Strategies for transferring all selected checkbox IDs to REST endpoint

I'm currently diving into web development and have set up a few checkboxes on my page. Right now, I have four checkboxes available. My goal is to send the IDs of the checkboxes that the user has checked to my "REST Service". Below is the code that I&a ...

After attempting to publish my NPM package, I encountered an issue where I received an empty object. This occurred despite utilizing a setup that includes ES6, Babel,

Is there anyone out there who can assist me with this issue? I am attempting to publish an npm package with the following configuration: webpack: production: { entry: [ './src', './src/app.scss', 'draft- ...

Difficulty in transferring JavaScript variable to PHP

After encountering a basic issue, I learned that PHP runs server-side and executes on pageload even if the include is nestled in an AJAX callback. Initially, I could display query results by returning PHP in the JavaScript value attribute, but failing to i ...

What is a sophisticated approach to overriding a jQuery method specifically within a plugin?

Today, my brain is in a bit of a fog where I can't seem to find an elegant solution to this issue. I've recently come into possession of a plugin that I need to tweak in order to pass an enabled or disabled state to it, allowing it to detach all ...

Notification for background processing of $http requests

I am searching for a solution to encapsulate all my AJAX requests using $http with the capability to display a loading gif image during processing. I want this functionality to extend beyond just $http requests, to cover other background processing tasks a ...

What is the method for sending a CSV file as Form Data through a REST API?

I am currently struggling with encoding my uploaded CSV file to Form Data. My approach is to pass the actual file to be processed on the backend using the post method of my API. However, I keep encountering an error message saying "TypeError: Failed to con ...

Encountering difficulty in assigning the desired value to the select box

// updating the subType value in the controller $scope.newEngagement.subType = 3; // creating a list of engagement subTypes $scope.engagementSubTypeList = [ { "subTypeId": 1, "subTypeName": "value1" }, { "subTypeId": 2, "subTypeName": "value2" }, { " ...

Tips for incorporating various Vue Js components into an outdated system

I have an old Java system with multiple pages that includes a Vue dashboard component on App.vue. The issue arises when I try to use Vue on another page without wanting the dashboard to appear there as well. After researching, I found conflicting informat ...

Send Ajax Form using php without the use of document.ready function

I've encountered an issue with my PHP Ajax form submissions on my webpage. The code works perfectly for forms that are preloaded on the page, but I'm having trouble with dynamic forms that are called using other JavaScript functions. I'm loo ...

How can I translate JSON in a Jbuilder template using Rails 4?

I am currently working on a file named 'show.json.jbuilder' in which I have included the following content: json.extract! @person, :id, :first_name, :last_name, :title, :birthday, :gender, :created_at, :updated_at While translating this content ...

Error: JSX elements that are next to each other must be contained within a parent tag

I am trying to display articles on a page using ReactJS, but I encountered an issue where I need to wrap enclosing tags. It seems like React doesn't accept identical tags next to each other. How can I effectively show tabular data? render() { r ...