我有一个从另一个 URL 获得的以下 json(样本数据)
var data = [
{ id: 1, name: 'ravi', parentid: 0 },
{ id: 2, name: 'raj', parentid: 1 },
{ id: 3, name: 'ram', parentid: 1 },
{ id: 4, name: 'raja', parentid: 0 },
{ id: 5, name: 'raju', parentid: 4 },
{ id: 6, name: 'dinesh', parentid: 4 }
];
当我收到 Angular 成功消息时,我想比较具有 id 的数据
parentid
为零,剩余数据为 parentid
。我尝试了以下代码,但我无法继续进行更多操作
$http.get('URL')
.success(function(data) {
var categories = data;
for(var i =0;i<=categories.length;i++)
{
if(typeof categories[i] != "undefined" && categories[i].parentId == 0)
{
$scope.cat.push(categories[i]);
}
if($scope.cat[i].parentid == categories[i].id)
{
$scope.content.push(categories[i]);
}
}
});
这里我想比较 categories[i].parentId
和 $scope.cat.id
并插入到数组中,但是在比较这个时我得到了一个错误,比如 $scope.cat[i]
是 undefined
最后我的输出如下所示
Ravi
raj
ram
raja
raju
dinesh
最佳答案
我面临以下 3 个问题:
- 在
if(typeof categories[i] != "undefined"&& categories[i].parentId == 0)
中,您正在比较parentId
并且它永远不会像您的属性名称是parentid
(检查大小写)。因此,您的第一个if
循环永远不会执行,这就是为什么您的$scope.cat
保持未定义的原因。
解决方案:更正parentId
的拼写错误
- 在
if($scope.cat[i].parentid == categories[i].id)
中,您正在比较父元素的父 id 与子元素的 id。
解决方案:if($scope.cat[i].id == categories[i].parentid)
- 您对两个具有不同长度的列表项使用相同的迭代器。
解决方案:
var categories = data;
// fill $scope.cat with elements having parent id = 0, so this list will contain all the parent elements
$scope.cat = categories.filter(function(category) {
return category && category.parentid === 0
});
$scope.content = [];
// fill $scope.content with elements whose parent exist in $scope.cat (the parent list craeted above)
categories.forEach(function(category) {
if ($scope.cat.filter(function(cat) {
return category.parentid === cat.id
}).length > 0)
$scope.content.push(category);
});
样本 plunk here
关于javascript - 比较angularjs中的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45873972/