2016-08-11 33 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

這個工作完美。謝謝! –