本文介绍在Angular项目中,如何将$scope.selected数组转化为JSON对象并Push到$scope.data.Menus数组中,以符合API要求的数据格式。通过示例代码展示了具体的实现步骤和注意事项。
Angular中JSON对象Push到数组的方法
在项目中,API要求的数据格式为
$scope.data = {
"name":"zhangsan",
"Menus": [{"id":1},{"id":2}]
}
而我的返回格式为
$scope.data=["name":"zhangsan"]
$scope.selected = [1,2,3];
需要将两个数组整合,其中$scope.selected要先转化为JSON对象,再进行Push操作。
代码如下:
// 将menu数组转化为json格式
self.convertJson = function (callback) {
//传入数组为$scope.selected,每循环一遍就push一次
angular.forEach($scope.selected, function (value, key) {
$scope.data.Menus.push({
'id':value
});
});
callback($scope.data);
};
以上这篇Angular JSON对象Push到数组的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持本站。