简体   繁体   English

如何在Javascript中将JSON字符串解析为数组

[英]How to parse JSON string into array in Javascript

Here is a Mocha test in my Javascript program: 这是我的Javascript程序中的Mocha测试:

 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: 然后我可以看到JSON字符串像这样打印出来:

[ { 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"]. 我想要一个包含所有JSON对象名称的字符串数组, 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. 如果尝试JSON.parse(),则会收到意外令牌o,因此我知道“ listOfCurrencies”已经是字符串。 What is happening? 怎么了?

Thanks 谢谢

You could use the map function to only extract the name property from the currency 您可以使用map函数仅从货币中提取name属性

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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