我对使用javascript零经验,真的可以使用一些帮助。照原样,这也是我第一次在堆栈上发帖。
我有以下学生列表:
var student = [{
id: 0,
name: "John",
skills: ["javascript", "html", "css", "c#"]
},
{
id: 1,
name: "Brian",
skills: ["javascript", "java", "c", "c#", "c++", "html"]
},
{
id: 2,
name: "Michael",
skills: ["c", "c++", "go", "rust"]
}
];
说明将返回以下按组排序的名称:
"c": ["Brian", "Michael"],
"c#": ["John", "Brian"],
"c++": ["Brian", "Michael"],
"css": ["John"],
"go": ["Michael"],
"html": ["John", "Brian"],
"java": ["Brian"],
"javascript": ["John", "Brian"],
"rust": ["Michael"]
};
到目前为止我尝试过的是:
function skills(student)
{
var result = student.reduce(function(map, obj) {
map[obj.skills] = obj.name;
return map;
}, {});
console.log(result2);
}
skills(student);
输出越来越接近预期,但我遇到了麻烦,可能需要一些帮助。
{ 'javascript,html,css,c#': 'John',
'javascript,java,c,c#,c++,html': 'Brian',
'c,c++,go,rust': 'Michael' }
迭代skills
中的每个reduce
。测试以查看要迭代的技能是否首先在地图中。如果不是,请将其值设置为空数组。然后,将学生的姓名推送到它:
var student = [{
id: 0,
name: "John",
skills: ["javascript", "html", "css", "c#"]
},
{
id: 1,
name: "Brian",
skills: ["javascript", "java", "c", "c#", "c++", "html"]
},
{
id: 2,
name: "Michael",
skills: ["c", "c++", "go", "rust"]
}
];
function skills(student) {
return student.reduce(function(map, { name, skills }) {
skills.forEach((skill) => {
if (!map[skill]) {
map[skill] = [];
}
map[skill].push(name);
});
return map;
}, {});
}
console.log(skills(student));
function groupBySkill(list) {
const regrouped = list.reduce((acc, cur) => {
cur.skills.forEach((skill) => {
if (acc[skill] === undefined) {
acc[skill] = [];
}
acc[skill].push(cur.name);
});
return acc;
}, {});
return regrouped;
}
您可以先使用.forEach
遍历学生,然后再使用另一个内部.forEach
遍历技能,并将学生的姓名存储在返回对象基于键的数组中:
var students = [{ id: 0, name: "John", skills: ["javascript", "html", "css", "c#"] }, { id: 1, name: "Brian", skills: ["javascript", "java", "c", "c#", "c++", "html"] }, { id: 2, name: "Michael", skills: ["c", "c++", "go", "rust"] } ];
function skills(students) {
var obj = {}
students.forEach(s => {
s.skills.forEach(sk => {
if (!obj[sk]) obj[sk] = [];
obj[sk].push(s.name);
});
});
return obj;
}
console.log(skills(students));