gpt4 book ai didi

javascript - 无法通过在 javascript 中识别对象的父 ID 将对象插入父数组

转载 作者:数据小太阳 更新时间:2023-10-29 06:05:58 27 4
gpt4 key购买 nike

我有一个 JSON 数组,其属性为 id 和 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: [],
}
]
}
]
}
];

我想根据 parentActiityId 推送一个新项目。新项目将有一个新的 id。示例:如果我的对象是这样的:

{
id: 7,
activityName: "Drilling",
parentActivityId: 1,
items: []
}

然后我的对象看起来像这样..

 $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: [],
}
]
}
]
}
];

我试过给这个 for 循环..

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);

这只会推送给父级。我想在 for 循环中识别子级,并通过识别 parentActivityId 推送到特定的数组对象。非常感谢任何帮助。

最佳答案

使用递归提议和 Array.prototype.reduce() :

var 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:[]}]}]}],
child = { id: 7, activityName: "Drilling", parentActivityId: 1, items: [] };

function getParent(r, a) {
return a.id === child.parentActivityId ? a : a.items.reduce(getParent, r);
}

var node = data.reduce(getParent, {});
'items' in node && node.items.push(child);

document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');

关于javascript - 无法通过在 javascript 中识别对象的父 ID 将对象插入父数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32092074/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com