我需要将 JSON 对象推送到 AngularJS,并且需要先检查其中一个对象的值是否存在。我需要覆盖数据。
$scope.setData = function(survey, choice) {
keepAllData.push({
'surveyId': survey.id,
'choiceId': choice.id
});
console.log(keepAllData);
toArray(keepAllData);
alert(JSON.stringify(toArray(keepAllData)));
$scope.keepAllDatas.push({
'surveyId': survey.id,
'choiceId': choice.id
});
var items = ($filter('filter')(keepAllDatas, {
surveyId: survey.id
}));
}
function toArray(obj) {
var result = [];
for (var prop in obj) {
var value = obj[prop];
console.log(prop);
if (typeof value === 'object') {
result.push(toArray(value));
console.log(result);
} else {
result.push(value);
console.log(result);
}
}
return result;
}
如果keepalldata 中存在调查ID,我需要使用choiceid 更改最近的值。是否可以使用 AngularJS?
最佳答案
试试这个:在推送数据之前,您必须检查调查 ID 是否存在。如果存在,您必须使用相应的调查 ID 更新选择,否则您可以直接推送。
$scope.setData = function(survey, choice) {
var item = $filter('filter')(keepAllData, {
surveyId: survey.id
});
if (!item.length) {
keepAllData.push({
'surveyId': survey.id,
'choiceId': choice.id
});
} else {
item[0].choiceId = choice.id;
}
console.log(keepAllData);
}
Demo
关于angularjs - 如何将 JSON 对象推送到 AngularJS 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38700877/