2016-09-25 93 views
1

我有一個JavaScript問題。代碼如下:獲取_.groupBy的值

var myDB = [ 
    { xCounter: 'positive', day: 'first' }, 
    { xCounter: 'positive', day: 'second' } 
]; 

var days = _.groupBy(myDB, 'day'); 

如何獲得「days」的第一,第二,第三...值?

謝謝!

+0

嗨,你可以提供一個myDB變量內的例子嗎? – Brunt

+0

Hi @Brunt,這裏是一個例子:myDB = [{「xCounter」:「positive」,「day」:「first」},{「xCounter」:「positive」,「day」:「second」}] –

回答

1

根據示例你給:

var myDB = [{ "xCounter": "positive", "day": "first" }, { "xCounter": "positive", "day": "second" }]; 

使用groupBy方法,你會得到以下結果在days變量:

{ 
    first: [{ "xCounter": "positive", "day": "first" }], 
    second: [{ "xCounter": "positive", "day": "second" }] 
} 

要經過這樣的結果,你可以使用以下片段:

for (var day in days) { 
    if (days.hasOwnProperty(day)) { 
    // do something with 'day' (which will take tha values 'first' and 'second') 
    // and 'days[day]' (which is an array of {xCounter: X, day: Y} objects) 
    } 
} 

PS:我會建議(https://lodash.com/docs/4.16.1#groupBy)作爲Lodash發展更積極,但這是我的意見;)

+0

謝謝!它正在工作! –