我正在尝试从一个数组创建一个新数组,该数组将按键分组,新数组的索引将是旧数组的键,如下所示
旧数组
Array1
0 :term_id: "1"
capacity:"11"
price: "452"
1 :term_id: "2"
capacity:"33"
price: "44"
2 :term_id: "1"
capacity:"1"
price: "2"
我希望按 term_id
对该数组进行分组,因此新数组是
新数组
Array2
1 :terms >
0: capacity:"11"
price: "452"
1: capacity:"1"
price: "2"
2 :terms >
0: capacity:"33"
price: "44"
如您所见,在新数组中,该数组按 term_id 的索引进行分组,并且内部还有另一个数组及其内容
我尝试使用groupBy
方法,但无法保留旧数组的索引
最佳答案
您可以使用函数reduce
来分组并构建所需的输出。
var Array1 = [{ term_id: "1", capacity: "11", price: "452"}, { term_id: "2", capacity: "33", price: "44"}, { term_id: "1", capacity: "1", price: "2"}];
var result = Object.values(Array1.reduce((a, {term_id, capacity, price}) => {
(a[term_id] || (a[term_id] = {terms: []})).terms.push({capacity, price});
return a;
}, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 根据数组的键对数组进行分组,并使用组作为索引创建一个新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49558557/