3 回答
TA贡献1810条经验 获得超4个赞
看起来您对遍历数组与键入对象有点困惑。
let organizeInstructors = function(instructors) {
let output = {}; // so the obvious which is to create the object
for(let i = 0; i < instructors.length; i++) {
const instructor = instructors[i]
if(!output[instructor.course]) {
output[instructor.course] = []
}
output[instructor.course].push(instructor.name)
}
return output;
}
console.log(organizeInstructors([
{name: "Samuel", course: "iOS"},
{name: "Victoria", course: "Web"},
{name: "Karim", course: "Web"},
{name: "Donald", course: "Web"}
]))
添加 constinstructor也使其更易于阅读
TA贡献1155条经验 获得超0个赞
使用reduce
data = [ { name: "Samuel", course: "iOS" }, { name: "Victoria", course: "Web" }, { name: "Karim", course: "Web" }, { name: "Donald", course: "Web" }, ];
getObj = (data) =>
data.reduce(
(r, c) => (
!r[c.course] // checks if accumulator doesn't have c.course as key
? ((r[c.course] = []), r[c.course].push(c.name)) // then make an array that corresponds the key then push c.name
: r[c.course].push(c.name), // else push c.name to the corresponding array
r
),
{}
);
console.log(getObj(data));
TA贡献1830条经验 获得超9个赞
这使用Array.prototype.reduce方法。
请注意,这不会检查该值是否已存在于课程数组中,只会盲目添加。这可能意味着您在同一课程中获得多个同名实例。
const organizeInstructors = function(instructors) {
return instructors.reduce((cumulative, current) => {
// if we don't have a course in cumulative object, add it.
if (!cumulative[current.course]) cumulative[current.course] = [];
// add in the current name.
cumulative[current.course].push(current.name);
// return the cumulative object for the next iteration.
return cumulative;
}, {});
}
console.log(organizeInstructors([{
name: "Samuel",
course: "iOS"
},
{
name: "Victoria",
course: "Web"
},
{
name: "Karim",
course: "Web"
},
{
name: "Donald",
course: "Web"
}
]));
添加回答
举报