How to retrieve data from a nested object within a JSON array using JavaScript

When I use Logger.log(response.data.phone), the following data is displayed in my log:

[{label=work, primary=true, value=5558675309}, {label=work, value=6108287680, primary=false}, {value=6105516373, label=work, primary=false}]

My goal is to have the two phone numbers returned as 5558675309, 6108287680.

I have attempted

Logger.log(response.data.phone.value)
to no avail. Also, I have tried ...phone['value'] and ...phone[0].value, which does return the first phone number 5558675309. However, I would like it to return all value values whenever I input the phone key. How can I modify the logger to achieve this?

Answer №1

response.data.phone contains an array that can be iterated through using a loop:

Logger.log(response.data.phone.map(phone => phone.value).join(', '));

const response = {data: {phone : [{label:'work', primary:true, value:5558675309}, {label:'work', value:6108287680, primary:false}, {value:6105516373, label:'work', primary:false}] } }

const Logger = { log : console.log};

Logger.log(response.data.phone.map(phone => phone.value).join(', '));

Answer №2

response.data is actually an array, but keep in mind that response.data.phone does not exist. To access the phone property of each element in the array, you need to use response.data[n].phone where n is an integer. This can easily be achieved using a forEach loop.

response.data.forEach((element) => Logger.log(element.phone.value));

If you require support for older browsers, you can use the older function syntax like this:

response.data.forEach(function(element){
    Logger.log(element.phone.value)
});

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

When using ESLint together with React, you may encounter errors related to `no-unused-vars

I've configured eslint and eslint-plugin-react. After running ESLint, I'm encountering no-unused-vars errors for all React components. It seems that the linter is not recognizing JSX or React syntax. Any solutions? For example: app.js import ...

`What is the process for converting a CURL command with a token into Swift?`

Having received a CURL command from our custom REST API without any accompanying documentation, I am now faced with the task of translating and implementing it in Swift. In my previous experimentation with other APIs, I have used SwiftyJSON. However, I am ...

Submit a form using Ajax without having to reload the page

Seeking help for implementing an ajax form submission with four answer options to a question. The goal is to submit the form without reloading the page upon selecting an option. Below is the code I have been working on. Any suggestions or solutions are wel ...

Reload the text content of a locally hosted webpage within an iframe at regular intervals

I have set up a simple webpage on my local machine to showcase the contents of some text files on a dedicated monitor. However, I am facing an issue where refreshing the entire webpage causes flickering. My goal is to only refresh the iframes and reload t ...

What is the correct way to invoke a function from an external JavaScript file using TypeScript?

We are currently experimenting with incorporating Typescript and Webpack into our existing AngularJS project. While I have managed to generate the webpack bundle, we are facing an issue at runtime where the program is unable to locate certain functions in ...

When array elements are assigned to an object's attribute, they are not preserved

In my code, I have created an instance of an array called shortFacilitiesArray to make modifications to an existing array by adding additional values. However, when I assign this instance array as the attribute of my object, all the data is unexpectedly lo ...

AngularJS - Swipe to update

I've been trying to use the pull to refresh plugin for Angular JS, but unfortunately it's not working for me. Even though I can see the text, when I try to pull nothing happens! I followed all the steps outlined on this GitHub page: https://githu ...

Creating a sidebar navigation in HTML and CSS to easily navigate to specific sections on a webpage

Here's a visual representation of my question I'm interested in creating a feature where scrolling will display dots indicating the current position on the page, allowing users to click on them to navigate to specific sections. How can I achieve ...

Problem: Both select lists are moving all items

The code below pertains to a dual select list, as depicted in the image at this link: https://i.sstatic.net/edd21.png It is functioning as intended. The only issue is that when I click on the last subject in the right-hand side list box (select Subject l ...

Understanding and Decoding Nested Arrays within JSON using Swift

Looking to Decode JSON using code with a structure like this: userApiService.getAllUsers { (responseDict:NSDictionary?, error:NSError?) -> Void in //Parsing responseDict for the key "result" } This is the JSON Structure we are working wi ...

Create a search preview in JavaScript that emphasizes key information and provides a condensed overview

I am currently working on incorporating a feature that generates a highlighted and condensed preview of a provided text. Below is the code snippet I have so far: <div> Search: <input value='vestibulum' disabled/> </div> < ...

Sending an array using PHP through AJAX in jQuery to a separate PHP script

I am struggling with sending a PHP array to another PHP file using AJAX and jQuery. When I send the PHP array via jQuery post using a hidden input type value, it gets converted into a string. Therefore, the receiving PHP file does not receive it as an arra ...

Why isn't pagination typically positioned inside of a tbody element rather than before or after it?

I've created a user table that is based on the number parameter. I added a filter that listens to input and performs an AJAX call each time with the filter applied to the name field. However, the pagination is initially displayed ABOVE the entire ta ...

What strategies can be employed to manage three conflicting versions of a single library within a Vite project?

I am currently facing a unique challenge in my web app development process. Specifically, I am using the Vite framework with the svelte-ts template setup to build an application that integrates different libraries for WebXR based augmented reality. The goa ...

The integration of PHP code with an HTML form is causing issues

When I use the insert_teacher('bla bla','bla bla','dqsd') function in a PHP file, everything works fine. However, when I try to implement it with an HTML form, nothing is displayed and no data is inserted into my database. &l ...

Enhancing Sharepoint List with Multilingual Column Formatting

I am currently exploring the use of column formatting JSON to display different text content based on the user's browser language. Interestingly, I have found that the columns successfully translate when switching between a French browser and an Engli ...

I aim to continuously refresh a dynamic canvas line chart with JSON data

Having trouble with my code - the chart isn't updating. I'm new to using canvasJS charts and could use some help. <%@ page language=”java” contentType=”text/html; charset=UTF-8″ pageEncoding=”UTF-8″%> <%@ page import=”java ...

Tips for implementing xpath in module.exports with mocha javascript

Currently, I am utilizing mocha in conjunction with Node.js and have encountered a challenge. In my scenario, I need to use the XPath defined in one test file (verification.js) and apply it in another file (test.js). The issue arises from the fact that the ...

Jolt Spec - Assistance Required for Flattening an Array

Struggling with flattening the JSON data and need help to create a JOLT spec. I have tried various examples but haven't achieved the desired results. To test this, I am using the website . The sample JSON Input is as follows: { "metadata": { "t ...

Is it possible to implement the splice() method within a forEach loop in Vue for mutation

Hey there! I'm looking for a more efficient way to replace objects that match a specific index with my response data. Currently, I'm attempting to use the splice() method within a forEach() loop in Vue.js. However, it seems to only remove the obj ...