从对象数组Javascript创建嵌套的对象数组

时间:2020-08-09 01:12:04

标签: javascript highcharts

我有以下对象数组。如何重整数据以获得预期的输出?

let performanceReview = [ 
{ "name": "Sean", "Manager": "Joe", "Performance": 5}, 
{ "name": "John", "Manager": "Joe", "Performance": 9}, 
{ "name": "Paul", "Manager": "Joe", "Performance": 0}, 
{ "name": "Derek", "Manager": "Greg", "Performance": 10}, 
{ "name": "Lisa", "Manager": "Greg", "Performance": 10}, 
{ "name": "Julia", "Manager": "Donna", "Performance": 7}];

预期产量

var Series = [ 
{Manager: "Joe", data: [["Sean", 5], ["John", 9], ["Paul", 0]]}, 
{Manager: "Greg", data: [["Derek", 10],["Lisa", 10]]}, 
{Manager: "Donna", data: [["Julia", 7]]}];

也可以有人帮助我逐步解决问题的方法。

1 个答案:

答案 0 :(得分:1)

此解决方案将任务分为两个步骤。 (代码可能会更短一些,但是比起将所有逻辑压缩到一个直线上来,这可能更容易理解。)

  1. 使用Array.prototype.reduce,我们可以创建一个对象,其中每个属性都具有:
  • 经理的名字作为关键字,
  • 以分数为值的小黄人的二维数组
  1. 然后,使用for...in语法,我们可以将每个属性转换为一个独立的对象并将其推入到输出数组。

有关说明,请参见代码中的注释。

// Main
const
  originalArray = getOriginalArray(),
  obj = groupByManager(originalArray),
  output = formatFinalArray(obj);

console.log(output);

// We make an object because, unlike Arrays, they use named properties
function groupByManager(input){
  const obj = input.reduce(

    // 1st argument to `reduce` is a 'reducer' function (taking two args)
    //   that will be applied to each item of the array
    (grouped, item) => {
      // 1st arg to reducer func is the accumulated value, returned after each loop
      // 2nd arg to reducer func is the item of the array for the current loop 

      // If there's no prop named for this manager, makes one w/ empty array as value
      grouped[item.Manager] = grouped[item.Manager] || [];

      // Makes a two-item array of name and performance and pushes it to prop array
      grouped[item.Manager].push([item.name, item.Performance]);

      // The accumulated object has been updated, is ready to be used in next loop
      return grouped;
    },
    // 2nd arg to `reduce` (an empty obj) to be used as `grouped` during first loop
    {}
  );
  return obj;
}

// We'll pass the object into this function to get our desired format
function formatFinalArray(obj){
  const output = [];
  for(let key in obj){
    output.push({ Manager: key, data: obj[key] });
  }
  return output;
}

// Just provides our original array
function getOriginalArray(){
  return [
    { "name": "Sean",  "Manager": "Joe",   "Performance": 5  }, 
    { "name": "John",  "Manager": "Joe",   "Performance": 9  }, 
    { "name": "Paul",  "Manager": "Joe",   "Performance": 0  }, 
    { "name": "Derek", "Manager": "Greg",  "Performance": 10 }, 
    { "name": "Lisa",  "Manager": "Greg",  "Performance": 10 }, 
    { "name": "Julia", "Manager": "Donna", "Performance": 7  }
  ];
}