[英]Adding a new property into a javascript object based on existing property of siblings
可以說我有一個復雜的對象數組,如下所示:
[
{
"title": "Fundamentals",
"order": 1,
"lessonRef": "fundamentals",
"children": [
{
"title": "History",
"order": 1,
"lessonRef": "history",
"children": []
},
{
"title": "NEW NODE 1",
"lessonRef": "NEW NODE 1 STUB",
"children": []
},
{
"title": "Math",
"order": 2,
"lessonRef": "math",
"children": []
},
{
"title": "NEW NODE 2",
"lessonRef": "NEW NODE 2 STUB",
"children": []
}
{
"title": "Geography",
"order": 3,
"lessonRef": "geography",
"children": []
}
]
},
{
"title": "Basics",
"order": 2,
"lessonRef": "basics",
"children": []
}
]
我如何:
order
字段的new node
,並根據其在數組中的位置為其提供下一個數字, 我正在尋找一種lodash的方法來使我入門,然后再開始使用純JavaScript進行操作。
編輯:提供了我的解決方案-在我的情況下,保證數組順序,但我將問題擴展到不保證順序的情況。
如果這是您要執行的操作:
var yourArray = yourDataArr
var arr1 = []
//fix children first
_.each(yourArray, function(item) {
if(item.children) item.chilren = fixArr(children)
arr1.push(item)
})
//fix your array
yourArray = fixArr(arr1)
//fix function
function fixArr(arr) {
var res = []
var prevOrder
_.each(arr, function(item) {
var currentOrder = item.order
if(!currentOrder) {
item.order = prevOrder?prevOrder + 1:1
prevOrder = item.order + 0
}
res.push(item)
})
return res
}
//or maybe this is you want
function fixArrAlt(arr) {
var res = []
var order = 1
_.each(arr, function(item) {
item.order = order + 0
res.push(item)
order ++
})
return res
}
遵循@ jfriend00的建議,我只是遞歸地映射了數組中的所有元素,並將順序指定為索引:
function reapplyOrder(array){
return _.map(array, function (val, i) {
val.order = i+1;
if(val.children.length > 0){
val.children = reapplyOrder(val.children);
}
return val;
});
}
$scope.array = reapplyOrder($scope.array);
就我而言,數組順序是可以保證的,但是我將問題擴展到不保證順序的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.