在AngularJS中过滤掉一个数组

时间:2016-02-17 18:06:07

标签: javascript arrays angularjs

我有一个JSON对象,从我的Web服务返回给我,我已经将其添加到我的AngularJS项目中的数组中。

我需要创建一个如下所示的数组:

$scope.eventSources = [
//this is event source object #1
{
    events: [ // put the array in the `events` property
    {
        title: //POPULATE FROM MY ARRAY,
        start: //POPULATE FROM MY ARRAY,
        END: //POPULATE FROM MY ARRAY
    },
    {
        title: //POPULATE FROM MY ARRAY,
        start: //POPULATE FROM MY ARRAY,
        end: //POPULATE FROM MY ARRAY
    }
    ],
}];

来自一个如下所示的数组:

holidays: [
{
    HOLIDAY_END: "/Date(1461538800000+0100)/"
    HOLIDAY_EVENT_ID: 1
    HOLIDAY_START: "/Date(1461106800000+0100)/"
    HOLIDAY_TITLE: "Spain     "
    USER_ID: 1
}
]

因此,您可以看到HOLIDAY TITLE, HOLIDAY START AND HOLIDAY END需要添加到新数组中。

2 个答案:

答案 0 :(得分:2)

这应该适用于遍历holidays的forEach循环,并使用holidays中每个元素创建一个包含必填字段的对象。这段代码可以解决问题:

$scope.eventSources = [{events:[]}];    //set up object with array for containing data
var func = function() {    //Lets do it in a function so it's reusable
    holidays.forEach(function(hol) {    //forEach loop through the holidays array data

        $scope.eventSources[0].events.push({ //Push a new object to our eventSOurces array
            title: hol.HOLIDAY_TITLE, //Set up fields on new object
            start: hol.HOLIDAY_START,
            end: hol.HOLIDAY_END
        });    
    });
}
func(); //Call function to populate array

您在请求中切换ENDend,因此我与end一起使用,因为它与其他字段一致。

答案 1 :(得分:0)

这是Array#map()的提案



var data = {
        holidays: [{
            HOLIDAY_END: "/Date(1461538800000+0100)/",
            HOLIDAY_EVENT_ID: 1,
            HOLIDAY_START: "/Date(1461106800000+0100)/",
            HOLIDAY_TITLE: "Spain",
            USER_ID: 1
        }, {
            HOLIDAY_END: "/Date(1462538800000+0100)/",
            HOLIDAY_EVENT_ID: 2,
            HOLIDAY_START: "/Date(1461106800000+0100)/",
            HOLIDAY_TITLE: "France",
            USER_ID: 2
        }]
    },
    $scope = { eventSources: [{}] };

$scope.eventSources[0].events = data.holidays.map(function (a) {
    return {
        title: a.HOLIDAY_TITLE,
        start: a.HOLIDAY_START,
        end: a.HOLIDAY_END
    };
});
document.write('<pre>' + JSON.stringify($scope, 0, 4) + '</pre>');
&#13;
&#13;
&#13;