2016-09-25 19 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

谢谢!它正在工作! –

相关问题