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

时间:2016-08-11 14:50:30

标签: javascript arrays json

这是我的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());
});

如果我只使用

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

然后我可以看到JSON字符串被打印出来像这样:

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

我想获得一个包含所有JSON对象名称的字符串数组ie. ["US Dollar", "Canadian Dollar", "Australian Dollar"].

但是,使用我上面的专栏,它声称:

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

如果我尝试JSON.parse(),我会得到一个意外的令牌o,所以我知道" listOfCurrencies"它已经是一个字符串。发生了什么事?

由于

1 个答案:

答案 0 :(得分:3)

您可以使用map函数仅从货币

中提取name属性
.then((listOfCurrencies) =>      
    console.log(listOfCurrencies.map( currency => currency.name ));
);