JavaScript:提取数据&按不同属性分组

时间:2016-08-10 14:23:49

标签: javascript

我有一个JavaScript对象数组,看起来像这样。

[ { name: "A", tp1: 10, tp2: 20, ... tp31: 30 },
  { name: "B", tp1: 11, tp2: 21, ... tp31: 31 },
  { name: "C", tp1: 12, tp2: 22, ... tp31: 32 },
  { name: "D", tp1: 13, tp2: 23, ... tp31: 33 } ]

我想稍微重新排列数据。目前,你可以说“钥匙”(可以这么说)就是名字。我希望使用不同的属性对对象进行分组,比如tp1,并将对象中每个“name”的值作为自己的属性放入。

我的解释可能很糟糕,但基本上,我想将其转换为以下格式:

[ { x: "tp1" , A: 10, B: 11, C: 12, D: 13 },
  { x: "tp2" , A: 20, B: 21, C: 22, D: 23 },
  ...
  { x: "tp31", A: 30, B: 31, C: 32, D: 33 } ]

我真的不知道从哪里开始。

提前致谢。

1 个答案:

答案 0 :(得分:1)

let input = [
  { name: "A", tp1: 10, tp2: 20, tp31: 30 },
  { name: "B", tp1: 11, tp2: 21, tp31: 31 },
  { name: "C", tp1: 12, tp2: 22, tp31: 32 },
  { name: "D", tp1: 13, tp2: 23, tp31: 33 }
];
  
let output = Object.keys(input[0])  // get the properties of the first element
              .filter(key => key !== "name")  // "remove" the "name" property
              .map(key => {    // iterate over the remaining keys
                return input.reduce((result, current) => {    // and transform them into the required format
                  result[current.name] = current[key];
                  return result;
                }, { "x": key });    // "start" value for the first .reduce() round
              });

console.log(output);

使用的方法:

Object.prototype.keys() Object.keys()方法返回给定对象自己的可枚举属性的数组,其顺序与for...in循环提供的顺序相同(不同之处在于for-in循环也会枚举原型链中的属性。

Array.prototype.filter() filter()方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。

Array.prototype.map() map()方法创建一个新数组,其结果是在此数组中的每个元素上调用提供的函数。

Array.prototype.reduce() reduce()方法对累加器和数组的每个值(从左到右)应用函数以将其减少为单个值。