我想穿過一個JSON,如果某個條件適用,然後在該索引中推送一些額外的元素。將元素推入JSON對象
我有這樣的JS代碼:
$scope.addRoleToUser = function() {
var userid = $scope.selectedUser;
var tmpdata = [];
var index = 0;
//alert(userid);
angular.forEach($scope.users, function(data) {
if (data.id == $scope.selectedUser) {
tmpdata.push(data,{"roles":[{"id":"00","name":"newrole"}]});
}
else {
tmpdata.push(data);
}
index++;
});
$scope.users = tmpdata;
};
這是我最初的JSON元素:
$scope.users = [
{"id":"0","name":"User1","roles":[{}]},
{"id":"1","name":"User2","roles":[{}]},
]
我試圖讓它看起來像這樣的功能之後運行:
$scope.users = [
{"id":"0","name":"User1","roles":[{"id":"00","name":"newrole"}]},
{"id":"1","name":"User2","roles":[{}]},
]
但是,我得到這個:
[{"id":"0","name":"User1","roles":[{}]},{"roles":[{"id":"00","name":"newrole"}]},{"id":"1","name":"User2","roles":[{}]}]
你能提供一個小提琴嗎?我不確定$ scope.selectedUser是什麼樣子的。 –
''scope.selectedUser''是一個應該匹配其中一個''user.id''的數字 – user838437