目前我有很多人
const members = [{
imgUrl: 'resources/members/xxx.png',
name: 'xxx',
focus: [0, 1, 2, 4, 5]
}, {
imgUrl: 'resources/members/xxx.png',
name: 'xxx',
focus: [0, 1, 2, 3, 5]
}, {
imgUrl: 'resources/members/xxx.png',
name: 'xxx',
focus: [4, 6, 7, 8]
}];
您可以看到成员的焦点是持有一个数组。我将此数组用作包含技能的另一个数组的键列表。
const skills = [
'Skill 0',
'Skill 1',
'Skill 2',
'Skill 3'
];
在使用我的members
数组之前,我想用包含所有技能的字符串替换此焦点数组。
我想将每个焦点项目映射到一个包含技能的字符串。我想将此字符串数组转换为单个字符串,并在逗号后添加空格。
结果将是focus: 'Skill 1, Skill 3, Skill 7'
我去找了这个代码
const members = [{
imgUrl: 'resources/members/xxx.png',
name: 'xxx',
focus: [0, 2, 3]
}, {
imgUrl: 'resources/members/xxx.png',
name: 'xxx',
focus: [0, 1, 2]
}, {
imgUrl: 'resources/members/xxx.png',
name: 'xxx',
focus: [1, 3]
}];
const skills = [
'Skill 0',
'Skill 1',
'Skill 2',
'Skill 3'
];
const targetMembers = members.map(member =>
member.focus.map(skillIndex => skills[skillIndex])
.toString()
.split(',')
.join(', ')
);
console.log(targetMembers);
,但其他成员属性丢失。映射有什么问题,我该如何解决?
答案 0 :(得分:2)
由于您期望对现有member
数组进行更改,因此请在其上使用forEach()
:
const members = [{
imgUrl: 'resources/members/xxx.png',
name: 'xxx',
focus: [0, 2, 3]
}, {
imgUrl: 'resources/members/xxx.png',
name: 'xxx',
focus: [0, 1, 2]
}, {
imgUrl: 'resources/members/xxx.png',
name: 'xxx',
focus: [1, 3]
}];
const skills = [
'Skill 0',
'Skill 1',
'Skill 2',
'Skill 3'
];
members.forEach(member => {
member.focus.forEach((f, index) => member.focus[index] = skills[f]);
return member;
});
console.log(members);
答案 1 :(得分:1)
您需要将map
的结果分配给member.focus
。另外,请使用解构以避免修改原始对象。
const members = [{imgUrl:'resources/members/xxx.png',name:'xxx',focus:[0,2,3]},{imgUrl:'resources/members/xxx.png',name:'xxx',focus:[0,1,2]},{imgUrl:'resources/members/xxx.png',name:'xxx',focus:[1,3]}];
const skills = ['Skill 0','Skill 1','Skill 2','Skill 3'];
const targetMembers = members.map(({...member}) => {
member.focus = member.focus.map(f => skills[f]).join(', ');
return member;
});
console.log(targetMembers);