[英]How do I transform an array to hold data based on a value in the data?
我已经看到了一些看起来相似的问题,但是我所遇到的解决方案都不是。 我想根据我的一个值(年龄)对数组进行重新排列和重新创建的方式。 我想将同一“年龄”的所有数据放在一个地方。 所以这是我的示例数组:
[
{
"age": 15,
"person": {
name: 'John',
hobby: 'ski'
},
},
{
"age": 23,
"person": {
name: 'Suzi',
hobby: 'golf'
},
},
{
"age": 23,
"person": {
name: 'Joe',
hobby: 'books'
}
},{
"age": 25,
"person": {
name: 'Rosi',
hobby: 'books'
}
},{
"age": 15,
"person": {
name: 'Gary',
hobby: 'books'
}
},
{
"age": 23,
"person": {
name: 'Kane',
hobby: 'books'
}
}
]
而且我需要一个数组,其中年龄作为键,人作为值,因此每个键可以具有多个值,这意味着值本身就是数组。 我已经读过这个和这个问题以及更多,但它们并不完全相同。 我觉得我需要使用reduce来计算重复的年龄,然后根据该值对其进行过滤,但是如何获得这些年龄的值呢?
EIDT:
抱歉,不清楚:
这就是我需要的:
{
23: [
{ name: 'Suzi', hoby: 'golf' },
{ name: 'Joe', hobby: 'books'}
],
15: [
{ name: 'Gary', hobby: 'books' }
] ,
.
.
.
}
您实际上要减少而不是过滤。 过滤数组意味着删除元素并将保留的元素放入新容器中。 减少数组意味着将其转换为新容器中的单个值。 映射数组意味着将每个值转换为新容器。 由于您要更改数据的表示方式(即归约化),因此可以从一种形式转换为另一种更紧凑的形式。
假设您的值数组存储在let people = [...]
let peopleByAge = people.reduce(function (accumulator, value, index, array){
// The first time through accumulator is the passed extra Object after this function
// See the MDN for Array.prototype.reduce() for more information
if (accumulator[value.age] == undefined){
accumulator[value.age] = [];
}
accumulator[value.age].push(value);
return accumulator
}, {})
console.log(peopleByAge) // { 23: [{ age: 23, name: ..., hobby: ...}, ...], 13: [...], ...}
感谢@RobertMennell耐心地回答了我,我投了赞成票。 但是我只是想写我的版本,而MDN就是一个很好的例子。 它是一个较长的版本,假设人员是数组名称:
const groupedByvalue = 'age';
const groupedArray = people;
const groupBy = (peopleArray, value) => {
return peopleArray.reduce((acc, obj) => {
const key = obj[value];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}
console.log(groupBy(groupedArray,groupedByvalue));
更新:
使用三元运算符更精细:
const groupedByvalue = 'age';
const groupedArray = people;
const groupBy = (peopleArray, value) => {
return peopleArray.reduce((acc, obj) => {
const key = obj[value];
(!acc[key]) ? (acc[key] = []) : (acc[key].push(obj))
return acc;
}, {});
}
console.log(groupBy(groupedArray,groupedByvalue));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.