我看到了一些可能看起来相似的问题,但对于我的情况来说,没有一个是解决方案。我想重新分组并重新创建我的数组,按照我的值之一(年龄)排列或分组的方式。我想将相同“年龄”的所有数据放在一处。这是我的示例数组:
[
{
"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'
}
}
]
我需要一个以年龄为键、以人为值的数组,因此每个键可以有多个值,这意味着该值本身就是一个数组。 我已阅读this和this问题等等,但它们并不完全相同。 我觉得我需要使用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: [...], ...}
关于javascript - 如何转换数组以根据数据中的值保存数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52998861/