如何使用下划线从数组中获取值

时间:2015-04-16 15:59:28

标签: javascript underscore.js

我有从下面的数组返回Name,Stardate和Enddate的代码。我还想获得Id和Project Id。我被困了,因为我如何使用Underscore获取它们。

arr = [{
    "Id": "03bf3cf6-d95b-448f-b3b7-c3cebfce0034",
    "Name": "Define",
    "ProjectId": "a357ff1b-cbf8-4556-9edb-445b2efb3bfa",
    "StartDate": "2015-04-09",
    "EndDate": "2015-04-22",
    "Stage": ["03bf3cf6-d95b-448f-b3b7-c3cebfce0034=define=Define"]
}, {
    "Id": "a9aed2f0-7e3b-4149-b6e3-0e3cfd33bf68",
    "Name": "Plan",
    "ProjectId": "a357ff1b-cbf8-4556-9edb-445b2efb3bfa",
    "StartDate": "2015-04-22",
    "EndDate": "2015-04-29",
    "Stage": ["a9aed2f0-7e3b-4149-b6e3-0e3cfd33bf68=plan=Plan"]
}, {
    "Id": "a9aed2f0-7e3b-4149-b6e3-0e3cfd33bf68",
    "Name": "Plan",
    "ProjectId": "a357ff1b-cbf8-4556-9edb-445b2efb3bfa",
    "StartDate": "2015-04-30",
    "EndDate": "2015-05-14",
    "Stage": ["a9aed2f0-7e3b-4149-b6e3-0e3cfd33bf68=plan=Plan"]
}];

result = _.chain(arr)
    .groupBy(function (e) {
        return e.Name
    })
    .pairs()
    .map(function (e) {
        return {
            Name: e[0],
            StartDate: _.chain(e[1]).sortBy(function (e) {
                return new Date(e.StartDate).getTime();
            }).first().value().StartDate,
           EndDate: _.chain(e[1]).sortBy(function (e) {
                return -1 * new Date(e.EndDate).getTime();
            }).first().value().EndDate
        }
    })
    .value();

console.log(JSON.stringify(result));

1 个答案:

答案 0 :(得分:0)

实际上,我使用的是js库 - lodash,但是lodash与下划线是分开的,也许有相同的使用方式。

var _ = require('lodash');

_.map(arr, _.property('Id'));      //returns Id

[ '03bf3cf6-d95b-448f-b3b7-c3cebfce0034',
  'a9aed2f0-7e3b-4149-b6e3-0e3cfd33bf68',
  'a9aed2f0-7e3b-4149-b6e3-0e3cfd33bf68' ]

_.map(arr, _.property('ProjectId'));//returns ProjectId

[ 'a357ff1b-cbf8-4556-9edb-445b2efb3bfa',
  'a357ff1b-cbf8-4556-9edb-445b2efb3bfa',
  'a357ff1b-cbf8-4556-9edb-445b2efb3bfa' ]

_.pluck(arr,'Id')
_.pluck(arr,'ProjectId')
// shorter ...

我希望它可以帮助你〜