我有一个json对象,它包含多个父项(由parent属性表示为null),它有嵌套的子对象。
{
"aggregateId": null,
"aggregateList": {
"name": "My Grocery Store",
"children": [
{
"name": "Vegetables",
"documentType": "Produce",
"parent": null,
"count": 2,
"children": [{
"name": "Carrots",
"documentType": "Produce",
"parent": null,
"count": 1447,
"children": null
},
{
"name": "Lettuce",
"documentType": "Produce",
"parent": null,
"count": 311,
"children": null
}]
},
{
"name": "Canned Goods",
"documentType": "Cans",
"parent": null,
"count": 583,
"children": null
}
]
}
}
我要做的是当返回一个子对象的新对象时将其插入到现有数组中。例如,返回对象Celery
{
"name": "Celery",
"documentType": "Produce",
"parent": null,
"count": 100,
"children": null
}
遍历树,找到它的父(产生)并将其插入到该数组中。
{
"aggregateId": null,
"aggregateList": {
"name": "My Grocery Store",
"children": [
{
"name": "Vegetables",
"documentType": "Produce",
"parent": null,
"count": 2,
"children": [{
"name": "Carrots",
"documentType": "Produce",
"parent": null,
"count": 1447,
"children": null
},
{
"name": "Lettuce",
"documentType": "Produce",
"parent": null,
"count": 311,
"children": null
},
{
"name": "Celery",
"documentType": "Produce",
"parent": null,
"count": 100,
"children": null
}]
},
{
"name": "Canned Goods",
"documentType": "Cans",
"parent": null,
"count": 583,
"children": null
}
]
}
}
到目前为止,我已尝试使用for语句迭代集合,但这似乎不对,我没有得到返回的结果。看似不打架的部分是指定树中的位置。
有没有办法通过javascript获取对象/数组并查看每个属性以找到匹配的值,然后将新对象插入该数组?
更新
抱歉,我没有提供足够的代码。 for循环包含在函数
中 function nestAssociation(node, oldCollection, newAggregates)
{
var parent = node.documentType; //the parent value of the collection to be inserted
var currentCollection = oldCollection; //previous collection
var newCollection = newAggregates; //the object to be inserted (Celery)
for (var i = 0, iLen = arrayCount; i < iLen; i++) {
if ($scope.myList.children[0].children[i].documentType == node.documentType) {
console.log('true');
var myNewList = $scope.myList.children.concat(newCollection.children)
$scope.myList = myNewList;
console.log(myNewList)
}
}