Arthur Lee
Arthur Lee

Reputation: 121

How to parse JSON string into array in Javascript

Here is a Mocha test in my Javascript program:

 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());
});

If I just use the line

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

then I can see the JSON string being printed out as something like this:

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

etc.

I would like to get a string array containing the names of all the JSON objects, ie. ["US Dollar", "Canadian Dollar", "Australian Dollar"].

However, using the line I have above, it claims:

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

If I try JSON.parse(), I get an Unexpected token o, so I know that "listOfCurrencies" it is already a string. What is happening?

Thanks

Upvotes: 0

Views: 93

Answers (1)

Olivier Boissé
Olivier Boissé

Reputation: 18083

You could use the map function to only extract the name property from the currency

.then((listOfCurrencies) =>      
    console.log(listOfCurrencies.map( currency => currency.name ));
);

Upvotes: 3

Related Questions