Lodash按多个条件分组

时间:2018-12-19 09:13:26

标签: javascript lodash

我有此输入

var data = [
  { 
   'group': 
    {
     'id': 1,
     'name': 'admin'
    }, 
    'role': 'name1', 
    'screen': {
      'info': 'white',
      'name': 'Cat'
    }  
  },
  { 
   'group': 
    {
     'id': 1,
     'name': 'admin'
    }, 
    'role': 'name2',   
    'screen': {
      'info': 'Grey',
      'name': 'Dog'
    }  
  },
  { 
   'group': 
    {
     'id': 2,
     'name': 'client'
    }, 
    'role': 'name3',   
    'screen': {
      'info': 'Grey',
      'name': 'goldfish'
    }  
  }
];
//obj=>JSON.stringify({age: obj.age, address: obj.details[0].address})
//obj=>JSON.stringify({group: obj.name, displayname: obj})
var result=_.chain(data).groupBy("group.name").map(function(v, i) {
  return {
    group: i,
    role: _.get(_.find(v, 'role'), 'role'),
    screen: _.map( v, 'screen'),
  }
}).value();

document.body.innerHTML = '<pre>' + JSON.stringify(result, null, '  ') + '</pre>';
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>

这是我想要的输出:[ { "group": "admin", "screen": [ { "role": "name1", "ui": { "info": "white", "name": "Cat" } }, { "role": "name2", "ui": { "info": "Grey", "name": "Dog" } } ] }, { "group": "client", "screen": [ { "role": "name3", "ui": { "info": "Grey", "name": "goldfish" } } ] } ] 大家的任何帮助对我总是有帮助的。谢谢。 :(

1 个答案:

答案 0 :(得分:3)

您需要使用地图的回调函数来手动创建结果屏幕对象:

for (int i = 0; i <= 26; i++)
{
    cv::Mat img =
        cv::imread("../imgs/" + std::to_string(i) + ".jpg");
    cv::TickMeter tm;
    tm.reset();
    tm.start();
    std::vector<Window> faces = detector.DetectFace(img);
    tm.stop();
    std::cout << "Image: " << i << std::endl;
    std::cout << "Time Cost: "<<
              tm.getTimeMilli() << " ms" << std::endl;
    for (int j = 0; j < faces.size(); j++)
    {
        DrawFace(img, faces[j]);
    }
    cv::imwrite("/home/ryan/PCN-FaceDetection/predictions/i.jpg", img); // A JPG FILE IS BEING SAVED  
var data = [{"group":{"id":1,"name":"admin"},"role":"name1","screen":{"info":"white","name":"Cat"}},{"group":{"id":1,"name":"admin"},"role":"name2","screen":{"info":"Grey","name":"Dog"}},{"group":{"id":2,"name":"client"},"role":"name3","screen":{"info":"Grey","name":"goldfish"}}];

var result = _(data)
  .groupBy("group.name")
  .map(function(v, group) {
    return {
      group,
      screen: _.map(v, function(o) {
        return {
          role: o.role,
          ui: o.screen
        };
      }),
    }
  })
  .value();

console.log(result);
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}