我有一个kids
对象,如下所示:
const kids = {
name: 'john',
extra: {
city: 'London',
hobbies: [
{
id: 'football',
team: 'ABC',
},
{
id: 'basketball',
team: 'DEF',
},
],
},
};
我有以下对象,其中包含所有体育项目和额外信息。
const sports = [
{
name: 'volleyball',
coach: 'tom',
},
{
name: 'waterpolo',
coach: 'jack',
},
{
name: 'swimming',
coach: 'kate',
},
{
name: 'football',
coach: 'sara',
},
];
我想获取爱好数组中所有id
的列表并浏览体育数组中的每个体育项目,然后找到,为该对象available
添加一个额外的字段,提供值true
和相应的团队名称,结果如下:
const result = [
{
name: 'volleyball',
coach: 'tom',
},
{
name: 'waterpolo',
coach: 'jack',
},
{
name: 'swimming',
coach: 'kate',
},
{
name: 'football',
coach: 'sara',
available: true, // it exists in kids' hobbies
team: 'DEF' // get it from kids' hobbies
},
];
顺便说一句,这是我的尝试:
const result = kids.extra.hobbies.map(a => a.id);
for (var key in sports) {
console.log(sports[key].name);
const foundIndex = result.indexOf(sports[key].name);
if ( foundIndex > -1) {
sports[key].available = true;
}
}
console.log(sports)
但这不包括团队。如何将其添加到上面的代码中?
答案 0 :(得分:2)
使用.find
查找相应的爱好对象,然后提取其team
(如果存在):
const kids = {name:'john',extra:{city:'London',hobbies:[{id:'football',team:'ABC',},{id:'basketball',team:'DEF',},],},}
const sports = [{name:'volleyball',coach:'tom',},{name:'waterpolo',coach:'jack',},{name:'swimming',coach:'kate',},{name:'football',coach:'sara',},];
const { hobbies } = kids.extra;
const result = sports.map((sportObj) => {
const foundObj = hobbies.find(({ id }) => id === sportObj.name);
if (!foundObj) return { ...sportObj };
return {...sportObj, team: foundObj.team, available: true };
});
console.log(result);
没有传播:
const kids = {name:'john',extra:{city:'London',hobbies:[{id:'football',team:'ABC',},{id:'basketball',team:'DEF',},],},}
const sports = [{name:'volleyball',coach:'tom',},{name:'waterpolo',coach:'jack',},{name:'swimming',coach:'kate',},{name:'football',coach:'sara',},];
const { hobbies } = kids.extra;
const result = sports.map((sportObj) => {
const foundObj = hobbies.find(({ id }) => id === sportObj.name);
if (!foundObj) return Object.assign({}, sportObj);
return Object.assign({}, sportObj, { team: foundObj.team, available: true });
});
console.log(result);
答案 1 :(得分:0)
在您的代码result
数组中,kids.extra.hobbies
具有相同的数组索引(因为一个映射了另一个)。因此,您可以从业余爱好中查找具有foundIndex
的爱好对象:
const result = kids.extra.hobbies.map(a => a.id);
for (var key in sports) {
const foundIndex = result.indexOf(sports[key].name);
if ( foundIndex > -1) {
sports[key].available = true;
// lookup hobby at `foundIndex`
sports[key].team = kids.extra.hobbies[foundIndex].team;
}
}
console.log(sports)