_.orderBy嵌套对象属性乘lodash

时间:2018-12-20 10:06:45

标签: underscore.js lodash

我有这个数组:

[{
    "group": "admin",
    "menuorder": 8,
    "screen": [{
        "role": "name4",
        "order": 1,
        "ui": [{
          "info": "Grey",
          "name": "Dog",
          "MenuOrder": 5
        }]
      },
      {
        "role": "name1",
        "order": 9,
        "ui": [{
            "info": "white2",
            "name": "Cat2",
            "MenuOrder": 2
          },
          {
            "info": "white1",
            "name": "Cat1",
            "MenuOrder": 1
          }
        ]
      }
    ]
  },
  {
    "group": "client",
    "menuorder": 6,
    "screen": [{
      "role": "name2",
      "order": 3,
      "ui": [{
        "info": "Grey",
        "name": "goldfish",
        "MenuOrder": 2
      }]
    }]
  }
]

我想从MenuOrder 1、2、3 ...中订购此部分的位置

{
  "role": "name1",
  "order": 9,
  "ui": [{
      "info": "white2",
      "name": "Cat2",
      "MenuOrder": 2
    },
    {
      "info": "white1",
      "name": "Cat1",
      "MenuOrder": 1
    }
  ]
}

这是我的代码。每个人的任何帮助对我都很有帮助。谢谢。

let sorts = _.orderBy(result, function(e) { 
  return _.orderBy(e.screen.ui, function(c) {
   c.MenuOrder
  }, ['asc']);
}, ['asc']);

1 个答案:

答案 0 :(得分:0)

您可以使用_.cloneDeepWith创建一个完整的克隆,但是具有一个回调函数(定制程序),该函数将以不同的方式对待ui属性值:它将返回其排序后的版本:

const result = [{"group": "admin","menuorder": 8,"screen": [{"role": "name4","order": 1,"ui": [{"info": "Grey","name": "Dog","MenuOrder": 5}]},{"role": "name1","order": 9,"ui": [{"info": "white2","name": "Cat2","MenuOrder": 2},{"info": "white1","name": "Cat1","MenuOrder": 1}]}]},{"group": "client","menuorder": 6,"screen": [{"role": "name2","order": 3,"ui": [{"info": "Grey","name": "goldfish","MenuOrder": 2}]}]}];

const sorted = _.cloneDeepWith(result, v => {
    if (_.has(v, "ui")) return _.assign({}, v, { ui: _.sortBy(v.ui, "MenuOrder") });
});

console.log(sorted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>