Tips on how to iterate through a JSON object and store its values in an array

I am attempting to extract values from an external JSON file and store certain values in an array. Here is my code :

$.getJSON("https://link.to.my.json", function(data) {
    console.log(data); // this will display the information in the console
});

I am able to retrieve data from the JSON file, but I am unsure how to add the first and last names to the array [bob rooppo, peter sticker]. Any assistance on this matter would be greatly appreciated. Below is an example of the JSON data:

{
  "users": [
    {
      "test": "123",
      "name": {
        "first": "bob",
        "last": "roppo"
      },
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f2d202d0f28222e2623612c2020">[email protected]</a>",
      "phone": "+123456789"
    },
    {
      "test": "124",
      "name": {
        "first": "peter",
        "last": "sticer"
      },
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b7b6e7f6e794b6c666a626725686466">[email protected]</a>",
      "phone": "+123456789"
    }
  ]
}

Answer №1

You can easily utilize the Array#map method:

data.users.map(e =>
  (e.name.first ? e.name.first : '') + //Deals with the first name
  (e.name.first ? ' ' : '') +          //Adds a space between names
  (e.name.last ? e.name.last : '')     //Handles the last name
);

Example:

const data = {
  "users": [
    {
      "test": "123",
      "name": {
        "first": "bob",
        "last": "roppo"
      },
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ccaea3ae8caba1ada5a0e2afa3a1">[email protected]</a>",
      "phone": "+123456789"
    },
    {
      "test": "124",
      "name": {
        "first": "peter",
        "last": "sticer"
      },
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="06766372637446616b676f6a2865696b">[email protected]</a>",
      "phone": "+123456789"
    }
  ]
};

let result = data.users.map(e => (e.name.first ? e.name.first : '') + (e.name.first ? ' ' : '') + (e.name.last ? e.name.last : ''));
console.log(result);

Answer №2

To extract names from data, you can utilize the map method:

data.users.map( user => (user.name.first || "") + " " + (user.name.last || "") );

If both first and last names are always present in the data, you can simplify the code like this:

data.users.map( user => user.name.first + " " + user.name.last );

Here's a Demo:

var data = {
  "users": [
    {
      "test": "123",
      "name": {
        "first": "Bob",
        "last": "Roppo"
      },
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3a1aca683a4aea2aaafeda0acae">[email protected]</a>",
      "phone": "+123456789"
    },
    {
      "test": "124",
      "name": {
        "first": "Peter",
        "last": "Sticer"
      },
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9b9acbdacbb89aea4a8a0a5e7aaa6a4">[email protected]</a>",
      "phone": "+123456789"
    }
  ]
};

var output = data.users.map(user => user.name.first + " " + user.name.last);

console.log(output);

Answer №3

To iterate over the JSON data and extract user names, you can utilize the forEach() method:

var json = {
  "users": [
    {
      "test": "123",
      "name": {
        "first": "bob",
        "last": "roppo"
      },
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="187a777a587f75797174367b7775">[email protected]</a>",
      "phone": "+123456789"
    },
    {
      "test": "124",
      "name": {
        "first": "peter",
        "last": "sticer"
      },
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="09796c7d6c7b496e64686065276a6664">[email protected]</a>",
      "phone": "+123456789"
    }
  ]
}

var res = [];
json.users.forEach(function(p){
  var name = p.name.first + ' ' + p.name.last;
  res.push(name);
});
console.log(res);

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

The Express server's `GET` request at the root does not seem

When I access localhost:8080/chat?k=1&d=1, the console displays "CHAT PAGE" and everything works correctly. However, when I try to visit localhost:8080, the root event does not display "INDEX PAGE" as expected. Instead, it automatically retrieves ind ...

Transition effortlessly between web pages with subtle fading effects

I want to implement smooth page transition effects between two web domains: mcpixel.co.uk/new and mcpaper.co.uk. I am the owner of both domains. When a link in the header is clicked, I'd like the page to fade transition to the new page without any whi ...

Why is my backend sending two Objects in the http response instead of just one?

When I receive data from my Django backend, sometimes instead of one object I get two objects within the HTTP response. This inconsistency is puzzling because it occurs intermittently - at times there's only one object, while other times there are two ...

Executing multiple ajax calls and retrieving the results: A step-by-step guide

I am looking to run a series of Ajax calls and collect the responses before rendering the results for the user. The current code I am using is not working as expected because the render function is being executed before all the Ajax responses have been ga ...

Having a single quote within a double quote can cause issues with JavaScript code

I am currently developing a Django web app and facing an issue with sending a JSON object to my JavaScript code using a Django template variable. # views.py import json def get_autocomplete_cache(): autocomplete_list = ["test1", "test2", "test3", "te ...

Is it possible to use a Wcf polling duplex service with a client that is not using Silverlight?

I've been developing an online TicTacToe game and I'm utilizing a WCF polling duplex service to make it work. However, after dedicating a whole week to research, it seems that this service is only possible for Silverlight clients. If anyone is a ...

Having trouble documenting the procedures for adding a student and removing a student from an arrayList

I have set up an array list to store student information. private ArrayList<Student> studentList; Next, I initialized it within the constructor. Course(String courseName) { this.courseName = input.next(); this.studentList = new ArrayList<Stud ...

Iterating through a jQuery function to increment value

I have encountered an issue while trying to calculate the total value from an array of form fields. The problem lies in how the final value is being calculated on Keyup; it seems that only the last inputted value is being added instead of considering all t ...

Postpone the inclusion of html files within ng-include in AngularJS

I need to optimize the startup performance of my app by delaying the loading of a series of HTML files that are being included into my main controller. These files are not needed for at least 4 seconds while one specific HTML file processes. How can I de ...

Technique for dynamically incorporating Csrf tokens prior to every ajax request in CakePHP

I am currently using CakePHP 3.6 and have implemented a function that retrieves data via an AJAX call. This function can be triggered from any page on my website, where a button click opens a modal displaying the data fetched through the AJAX call. The iss ...

Retrieving Form Validation Error Value in AngularJS

Incorporating AngularJS 1.2 RC2 and utilizing Bootstrap for CSS, I have constructed a straightforward form as shown below: <form class="form-horizontal" name="form" novalidate> <label class="col-lg-2 control-label" for="name">Name</labe ...

Error in Sequelize database: Column name does not exist in the database

The issue at hand involves a findAll product selector with a column labeled "PermissionId" that does not actually exist. I am puzzled as to why Sequelize is generating this non-existent column. The errors encountered are as follows: Unhandled rejectio ...

Learning how to implement server-side processing with Django using datatables for beginners

Hello, I am new to Django and web development, seeking advice on how to implement server-side processing with my datatable. My challenge is to display 500k records from an external .db SQLite file on a Bootstrap datatable. In my views.py file, I currentl ...

Sending Svelte data to Javascript with an onclick event

In my Svelte store, I have an ASCII-Logo that I want to integrate into a button spanning two symbols ("-."). However, I do not want to split the ASCII into separate parts and just insert the button between them on my +page.svelte. Currently, I h ...

Utilize jQuery and HTML simplistically to display or conceal divs throughout a webpage

After developing some basic jQuery code using if-statements to toggle the visibility of Divs based on a select list in HTML, I am seeking ways to enhance this code: 1) How can I achieve the same functionality with fewer lines of code? 2) Rather than manu ...

Having trouble retrieving data from json_encode using jQuery AJAX and php

Having issues with an AJAX call from jQuery to PHP. The PHP responds with a JSON-encoded array, but the values are not accessible in jQuery. The status shows as OK, but the responseText is coming up as undefined. $(document).ready(function () { $( ...

AngularJS $routeParams is not defined

When trying to access $routeParams, I am receiving an undefined value. Check out my code below: var ngAddressBook = angular.module('ngAddressBook', ['ngRoute']); ngAddressBook.config(['$routeProvider', function($routePro ...

Highcharts is experiencing a duplication issue with the Y-Axis Series

This is a snippet from my code: $.get('https://dl.dropboxusercontent.com/u/75734877/data.csv', function (data) { var lines = data.split('\n'); $.each(lines, function (lineNo, line) { var items = line.split(',& ...

Converting an object with a combination of different index types into a string representation

I'm dealing with a unique object structure that behaves similarly to an array, except it contains a mix of index types (numbers and strings). Here's an example: var myObj = []; myObj[0] = 'a'; myObj[1] = 'b'; myObj[2] = &apos ...

Submit a post request using a Trigger.io-powered mobile application

Essentially, I need my mobile app (created with Trigger) to send a Post request to a remote server. The app generates GPS coordinates and timestamps, then sends this data to a server (built using Ruby on Rails) for storage. I am utilizing the Zepto library ...