lodash-创建新组并推送对象

丹尼·金(Danny Kim)
var data =  [
  {
    name : "Micah Richards",
    position : "Centre Back"
  },
  {
    name: "Kieran Richardson",
    position: "Left-Back"},
  {
    name: "Rudy Gestede",
    position: "Centre"},
  {
    name: "Jack Grealish",
    position: "Left Wing"},
  {
    name: "Brad Guzan",
    position: "Keeper"
  }
]

我上面有JSON对象。我如何使用lodash像下面的JSON对象那样进行转换

 var data =  {
   defenders: [
   {
     name: "Micah Richards",
     position: "Centre Back"
   },
   {
     name: "Kieran Richardson","position":"Left-Back"
   }
   ], 
 "midfielder" : 
    [{"name":"Rudy Gestede","position":"Forward"},
     {"name":"Jack Grealish","position":"Left Wing"}],
 "keeper":[ {"name":"Brad Guzan","position":"Keeper"}]}
米哈伊尔·沙布里科夫(Mikhail Shabrikov)

这里lodash的解决方案:

var data = [{
  name: "Micah Richards",
  position: "Centre Back"
}, {
  name: "Kieran Richardson",
  position: "Left-Back"
}, {
  name: "Rudy Gestede",
  position: "Forward"
}, {
  name: "Jack Grealish",
  position: "Left Wing"
}, {
  name: "Brad Guzan",
  position: "Keeper"
}];

var result = _.groupBy(data, function(item) {
  var positionType = '';

  switch (item.position) {
    case 'Centre Back':
    case 'Left-Back':
      positionType = 'defenders';
      break;
    case 'Forward':
    case 'Left Wing':
      positionType = 'midfielder';
      break;
    case 'Keeper':
      positionType = 'keeper';
      break;
  }

  return positionType;
});

console.log(result);

https://jsfiddle.net/dh0a1wfe/

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章