I'm having a JSON array with properties as id and parentActivityId.
$scope.data = [
{
id: 1,
activityName: "Drilling",
parentActivityId: 0,
items: [
{
id: 2,
activityName: "Blasting",
parentActivityId: 1,
items: [
{
id: 3,
activityName: "Ann",
parentActivityId: 2,
items: [],
},
{
id: 4,
activityName: "Ann",
parentActivityId: 2,
items: [],
}
]
},
{
id: 5,
activityName: "Transport",
parentActivityId: 1,
items: [
{
id: 6,
activityName: "Daniel",
parentActivityId: 5,
items: [],
}
]
}
]
}
];
I would like to push a new item based on the parentActiityId
.The new item will be having a new id
.
Example:If my object is like this:
{
id: 7,
activityName: "Drilling",
parentActivityId: 1,
items: []
}
then my object will look like this..
$scope.data = [
{
id: 1,
activityName: "Drilling",
parentActivityId: 0,
items: [
{
id: 2,
activityName: "Blasting",
parentActivityId: 1,
items: [
{
id: 3,
activityName: "Ann",
parentActivityId: 2,
items: [],
},
{
id: 4,
activityName: "Ann",
parentActivityId: 2,
items: [],
},
{
id: 7,
activityName: "Drilling",
parentActivityId: 2,
items: [],
}
]
},
{
id: 5,
activityName: "Transport",
parentActivityId: 1,
items: [
{
id: 6,
activityName: "Daniel",
parentActivityId: 5,
items: [],
}
]
}
]
}
];
I tried by giving this for loop..
var arrObj = {
id: 7,
activityName: "Drilling",
parentActivityId: 1,
items: []
};
function populateObj(arrObj) {
for (var i = 0; i < $scope.data.length; i++) {
if ($scope.data[i].id == arrObj.parentActivityId) {
$scope.data.push(arrObj);
}
}
};
populateObj(arrObj);
which will push only to the parent.I want to identify the child as well in the for loop and the push to the specific array object by identifying thr parentActivityId.Any help will be really appreciated.