我目前正在尝试使用 AngularJS 扩展/推送/合并一个对象,我的问题是,当我扩展时,它添加一个索引为 0 的对象,但我无法再添加,因为它们都获得相同的索引 0
//Original Object
{ "groups": {
"1": { "id": "1", "name": "object1"},
"2": { "id": "2", "name": "object2"}
}
}
//After running function
{ "groups": {
"0": { "id": "1", "name": "object0"}, //This is the new object no more can then be added
"1": { "id": "1", "name": "object1"},
"2": { "id": "2", "name": "object2"}
}
}
//What I want
{ "groups": {
"1": { "id": "1", "name": "object1"},
"2": { "id": "2", "name": "object2"},
"3": { "id": "3", "name": "object3"},
"4": { "id": "4", "name": "object4"} // etc
}
}
我目前正在使用这个:
$scope.addGroup = function () {
angular.extend($scope.audit.groups,[
{
"name": "",
"questions": []
}
]);
}
jsfiddle = https://jsfiddle.net/U3pVM/23760/
PHP 对象目前正在像这样构建,如果重组这将有助于我非常愿意这样做。
public function getAllQuestionGroupsByAuditIdArray($id) {
$questions = new Question();
foreach ($this->getAllQuestionGroupsByAuditId($id) AS $key => $group) {
$QuestionGroups[$key] = array(
"id" => $group['id'],
"name" => $group['name'],
"questions" => $questions->getQuestionsByGroupIdArray($group['id'])
);
}
return $QuestionGroups;
}
$this->response = array(
"name" => $auditData['name'],
"groups" => $questionGroups->getAllQuestionGroupsByAuditIdArray($id),
);
return print_r(json_encode($this->response));
最佳答案
在 PHP 中,我们可以更新响应以返回非关联数组或组,如下所示:
$QuestionGroups = array();
foreach ($this->getAllQuestionGroupsByAuditId($id) AS $key => $group) {
$QuestionGroups[] = array(
"id" => $group['id'],
"name" => $group['name'],
"questions" => $questions->getQuestionsByGroupIdArray($group['id'])
);
}
当转换为 JSON 时,这会将groups
作为对象数组而不是对象的对象返回。
然后,您可以简单地使用 .push()
将更多组附加到 groups
数组中。
关于javascript - 扩展/合并对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36404544/