我有一个对象数组,其中又包含父对象的 ID: 例如:-
$scope.result=[
{
"id": 1,
"name": ABC,
"type": PQR,
"parentId": 2
},
{
"id": 2,
"name": ABC,
"type": PQR,
"parentId": 1
}]
我想将此 JSON 转换为以下内容,其中我将使用 parentObject 代替 parentId
$scope.result=[
{
"id": 1,
"name": ABC,
"type": a,
"parentId": {
"id": 2,
"name": PQR,
"type": b,
"parentId": 1
}
},
{
"id": 2,
"name": PQR,
"type": b,
"parentId": {
"id": 1,
"name": ABC,
"type": a
}
}
]
任何人都可以帮助我进行此转换..
最佳答案
假设 parentId
将引用一个元素
angular.forEach($scope.result, function(result) {
var obj = $scope.result.filter(function(ele) {
return result.parentId === ele.id;
})[0];
result.parentId = obj;
});
因为你的标签不包含angularjs,我在这里使用Array.prototype.forEach
$scope.result.forEach(function(result) {
var obj = $scope.result.filter(function(ele) {
return result.parentId === ele.id;
})[0];
result.parentId = obj;
});
关于javascript - 通过比较父数组填充父对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29792839/