gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:04:52 26 4
gpt4 key购买 nike

我有一个 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 } ]

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

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

[ { 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 } ]

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

提前致谢。

最佳答案

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 循环也枚举原型(prototype)链中的属性)。

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

Array.prototype.map() : map() 方法创建一个新数组,其中包含对该数组中每个元素调用提供的函数的结果。

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

关于JavaScript:提取数据并按不同属性分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38876148/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com