基于兄弟姐妹的现有属性将新属性添加到javascript对象中

时间:2015-07-05 05:45:56

标签: javascript arrays sorting lodash

假设我有一个复杂的对象数组,如下所示:

[
  {
    "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": []
  }
]

我如何:

  1. 遍历每个节点,
  2. 检测到new node没有order字段,并根据数组中的位置为其提供下一个数字,
  3. 然后在此之后递增每个现有的兄弟姐妹
  4. 考虑下面任何其他新添加的节点?
  5. 我正在寻找一种让我开始使用lodash的方法,然后再先使用纯javascript进行操作。

    编辑:提供我的解决方案 - 在我的情况下,数组顺序是有保证的,但我会将问题扩展到无法保证订单的情况。

2 个答案:

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

在我的情况下,数组顺序是有保证的,但我会将问题扩展到无法保证订单的情况。