A guide on converting JSON strings into arrays using Javascript

In my JavaScript program, I have a Mocha test that checks if all available currencies are displayed in a drop-down list:

 it('displays all available currencies in drop down list', () => {
    return invoiceEditPage.details.currencyDropDown.dropDown.waitForEnabled()
    .then(() => invoiceEditPage.details.currencyDropDown.click())
    .then(() => getEnabledCurrencies(tenantUsers.admin.authUser))
    .then((listOfCurrencies) => console.log(listOfCurrencies["name"].split(",")))
    //.then((listOfCurrencies) => this.getCurrencyFromJSON(listOfCurrencies))
    //.then(() => console.log(invoiceEditPage.details.currencyDropDown.dropDownContents))
    //.then((listOfCurrencies) => assert.strictEqual(listOfCurrencies, invoiceEditPage.details.currencyDropDown.dropDownContents))
    .then(() => invoiceEditPage.details.currencyDropDown.dropDownMask.click());
});

When I use the following line:

.then((listOfCurrencies) => console.log(listOfCurrencies))

I see a JSON string being printed out like this:

[ { displayText: 'USD$',
name: 'US Dollar',
symbol: 'USD$' },

and so on.

My goal is to extract an array of strings containing the names of all the JSON objects, for example:

["US Dollar", "Canadian Dollar", "Australian Dollar"]
.

However, when using the above line, I encounter an error message stating:

"undefined: Cannot read property 'split' of undefined"

Even after trying JSON.parse(), I receive an Unexpected token o error, indicating that "listOfCurrencies" is already a string. Can anyone help me understand what's causing this issue?

Thank you

Answer №1

One way to efficiently extract the currency names is by utilizing the map function.

.then((listOfCurrencies) =>      
    console.log(listOfCurrencies.map( currency => currency.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

Utilizing Express.js: A Guide to Fetching File Downloads with a POST Method

Although GET requests are successful, I am facing challenges when using POST to achieve the same results. Below are the different code snippets I have attempted: 1. app.post("/download", function (req, res) { res.download("./path"); }); 2. app.post ...

Bring in React components using a specific namespace

Here is the structure of my React component: /build .............................. /lib /inner /InnerComponent.js /index.js /OuterComponent1.js /OuterComponent2.js /index.js ................................. package.jso ...

CakePHP and Legacy Ajax Script Integration

I have an old script that I want to integrate into a cakephp application. The script uses $_POST and I'm not very experienced with this, so I need some assistance with the integration. This is what the script consists of: THE JAVASCRIPT: prototype ...

Determining the orientation of an image in JavaScript

Currently, I am attempting to determine the orientation of images using JavaScript in order to apply a specific class to them. This process seems to be functioning correctly on Firefox, but is presenting challenges on other browsers. It appears to work bet ...

Receiving a JSON response from express.js via a jQuery get request is not functioning as expected

My goal is to send a JSON value from the back end to the front end of my application. Currently, I am using express.js and all post methods are working perfectly. When a button is clicked in the front-end of my application, I want to receive an invoice nu ...

Having trouble with npm and unable to find a solution that works. Any suggestions on how to fix it?

I've been working on a JavaScript project that requires me to import a library, but I keep running into errors with npm every time I try to use it. Here is the error message: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Recovering antiquated submission script in JavaScript

Here is a form with input data: <form id = 'myform'> ... <td><input type="checkbox" name="supplier_aid" value="on" checked disabled >{$output.t_artikelnr}</td> <td><input type="checkbox" n ...

Having trouble syncing a controller with AngularJS

Despite numerous attempts, I am still struggling to make a single controller function properly. Lately, I've been working on Angular projects and no matter what I do, my controllers just won't cooperate. In my latest project, everything is withi ...

Retrieving data via AJAX from an SD card

I am using the Atmel SAM4E-EK microcontroller as a server to host a webpage and send data over HTTP protocol. I am currently facing an issue with the download function while trying to download a file from my sd_card, which will not be larger than 512MB. s ...

Having trouble accessing the menu in the dropdown div when clicking back?

I am working on creating a menu that drops down from the top of the page using JQuery. I have everything set up with the code below: <div id="menu"> <div id="menucontentwrapper"> <div id="menucontent"></div> </di ...

"Utilizing Axios to convey JSON data into Vue Js: A Step-by-Step Guide

After saving my JSON data in a JS file for Vue, I encountered an issue with accessing it and getting my HTML v-for condition to work properly. The method described in the Vue.js documentation didn't help me fetch and execute the JSON data. Could someo ...

Troubleshooting issue: EJS loop not functioning correctly when handling JSON information

Having an issue with looping in an EJS file. Here's the data I'm working with: { "name": "Marina Silva", "info": [{ "periodBegins": "Sun Apr 14 23:48:36 +0000 2011", "periodFinishes": "Sun Apr 7 23:48:36 +0000 201 ...

"Internet Explorer text input detecting a keyboard event triggered by the user typing in a

It appears that the onkeyup event is not triggered in IE8/IE9 (uncertain about 10) when the enter button is pressed in an input box, if a button element is present on the page. <html> <head> <script> function onku(id, e) { var keyC = ...

The data retrieved using Ionic 3 Angular Fire's payload.val() seems to be returning

Is it possible to determine whether a profile is filled in or empty when using Firebase Database for storing profile information? Currently, I am utilizing profile.payload.val(), but it seems to return null in both cases instead of true when the profile is ...

What is the correct way to bind pairs (arrays of tuples or multidimensional arrays) in SQLAlchemy?

Can you show me an example of constructing a MySQL query with SQLAlchemy? SELECT * FROM table WHERE (key->>"$.k1", key->>"$.k2") IN ((1, "string1"), (2, "string2")) I attempted to use the text method but encountered an issue: select([table.c ...

Unlock the ability to retrieve the current Ember route directly within a component

I have a unique custom Ember component embedded within a controller. Currently, I am attempting to dynamically retrieve the name of the current route. In order to access the controller, I use: this.get('parentView') However, I am facing diffi ...

Switch Button Hyperlink in HTML/CSS

I have the following code: document.addEventListener("DOMContentLoaded", function(event) { (function() { requestAnimationFrame(function() { var banner; banner = document.querySelector('.exponea-banner3'); banner.classList ...

Querying with Spring JPA - Dynamically passing the index for JSON_REMOVE function

I have been using the JSON_REMOVE method to remove a specific field from my JSON array column. Below is the JPA query I initially used: @Modifying @Transactional @Query("UPDATE Data d SET d.month = JSON_REMOVE(d.month, '$[0].revenue') " ...

Which HTTP headers pertain to the loading of iframes? nuxt-helmet

Can anyone explain which security headers are associated with iframe loading issues and may prevent the iframe from being loaded? I implemented nuxt-helmet to configure security headers in my nuxt project. However, after uploading my site to a server loca ...

Display the JSON response received from a post request by showing each result in a separate div on the webpage

I am currently dealing with a post request to an API that returns Json data. I am looking for guidance on how to parse this json payload as it is in array format. My goal is to display each element of the array (result.payload) and have it displayed within ...