tl;博士
var ancestry = [{ ... }, { ... }, ...],
ages = {};
ancestry.forEach(function (person) {
var century = Math.ceil(person.died / 100),
age = person.died - person.born;
!ages[century] && (ages[century] = []);
ages[century].push(age);
});
console.log(ages);
我们将描述您的代码以了解问题:
假设我们有一个 ancestry 数组(这意味着 var ancestry = [{...}, {...}, ...] 是这种形式,每个项目看起来像这样:
var ancestry = [{
name: "Carolus Haverbeke",
sex: "m",
born: 1832,
died: 1905,
father: "Carel Haverbeke",
mother: "Maria van Brussel"
}, {
name: "Carolus Haverbeke",
sex: "m",
born: 1722,
died: 1805,
father: "Carel Haverbeke",
mother: "Maria van Brussel"
}, {
name: "Carolus Haverbeke",
sex: "m",
born: 1666,
died: 1705,
father: "Carel Haverbeke",
mother: "Maria van Brussel"
}, {
name: "Carolus Haverbeke",
sex: "m",
born: 1622,
died: 1715,
father: "Carel Haverbeke",
mother: "Maria van Brussel"
}];
使用不同的数据。
要实现您想要的,请按照以下步骤操作:
// Create your variable in the parent scope to allow variables to exist after the end of `forEach` method.
var ages = {};
// In the ancestry Array, we will loop on all items like `{ ... }`.
ancestry.forEach(function (person) {
// For each loop `person` will contain the current `{ ... }` item.
// Because we want add this property to the existant object, we don't need a new object. And as you said,
// 1. `ages` will be deleted in each loop because is defined into `forEach`
// var ages = {};
// We get the century of die.
var century = Math.ceil(person.died / 100),
// and age of die
age = person.died - person.born;
// now if the century property not exist, create a new array into to accept all centuries after.
if (!ages[century]) {
ages[century] = [];
}
// equivalent to `!ages[century] && (ages[century] = []);`
// in all cases, just push the value to the end.
ages[century].push(age);
});
// Still exist !
console.log(ages); // Object {18: Array(2), 19: Array(1), 20: Array(1)}
你的最终格式是你想要的:
{
18: [39, 93],
19: [83],
20: [73]
}