2016-08-11 2 views
0

에 배열로 JSON 문자열을 구문 분석하는 방법 여기 내 자바 스크립트 프로그램에서 모카 테스트입니다 :는 자바 스크립트

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

당신은

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

이것은 완벽하게 작동합니다. 감사! –