2016-08-11 57 views
0

这里是我的JavaScript程序的摩卡测试:如何解析JSON字符串数组中的Javascript

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

'listOfCurrencies'是一个数组,所以你不能做'listOfCurrencies [“名称”]' 。你可以做'listOfCurrencies [index] [“name”]'。您需要遍历数组或使用'map'函数。 – Kyriakos

+0

我相信当我早些时候尝试过,如果我尝试索引到listOfCurrencies是因为它认为它不是数组,它会抱怨。 –

回答

3

您可以使用地图功能仅从货币提取name属性

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

这个工作完美。谢谢! –