我有一个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
需要添加到新数组中。
答案 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
您在请求中切换END
和end
,因此我与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;