简体   繁体   中英

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"]. 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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM