lodash - 创建新组并推送对象

时间:2016-06-27 07:47:44

标签: javascript json lodash

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"}]}

2 个答案:

答案 0 :(得分:0)

在普通的Javascript中,您可以使用对象作为组引用并在其上构建结果。

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" }],
    groups = { "Centre Back": "defenders", "Left-Back": "defenders", "Forward": "midfielder", "Left Wing": "midfielder", "Keeper": "keeper" },
    grouped = {};

data.forEach(function (a) {
    grouped[groups[a.position]] = grouped[groups[a.position]] || [];
    grouped[groups[a.position]].push(a);
});

console.log(grouped);

答案 1 :(得分:0)

这里是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/