假设我有一个复杂的对象数组,如下所示:
[
{
"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": []
}
]
我如何:
new node
没有order
字段,并根据数组中的位置为其提供下一个数字,我正在寻找一种让我开始使用lodash的方法,然后再先使用纯javascript进行操作。
编辑:提供我的解决方案 - 在我的情况下,数组顺序是有保证的,但我会将问题扩展到无法保证订单的情况。
答案 0 :(得分:0)
如果这是你想做的事情:
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
}
答案 1 :(得分:0)
按照@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);
在我的情况下,数组顺序是有保证的,但我会将问题扩展到无法保证订单的情况。