我有一个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
},
];
顺便说一句,这是我的尝试:
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 :(得分:1)
这可以通过多种方式完成;然而,一个简单的方法是将问题分为两个步骤:
我们可以先使用Array.map()
功能将孩子的爱好变成一个阵列:
const hobbies = kids.extra.hobbies.map(hobby => hobby.id);
然后,我们可以迭代sports数组并将active
属性添加到新hobbies
数组中的任何对象:
const result = sports.map(sport => {
if (hobbies.indexOf(sport.name) !== -1) {
sport.available = true;
}
return sport;
})
完整解决方案
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.hobbies.map(hobby => hobby.id);
const result = sports.map(sport => {
if (hobbies.indexOf(sport.name) !== -1) {
sport.available = true;
}
return sport;
})
console.log(result);

答案 1 :(得分:1)
首先构建一个找到的体育数组,然后map
,同时检查体育对象的名字是否在其中:
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 sportsInHobbies = kids.extra.hobbies.map(({ id }) => id);
const result = sports.map((sportObj) => {
const available = sportsInHobbies.includes(sportObj.name);
return available ? {...sportObj, available } : { ...sportObj };
});
console.log(result);
答案 2 :(得分:1)
首先,我会将数据结构更改为对象。每当你有一个具有唯一ID的事物列表时,对象将使你的生活比数组更容易。考虑到这一点,如果必须使用数组,则可以执行以下操作:
const hobbies = kids.extra.hobbies
sports.forEach(s => s.available = hobbies.some(h => h.id === s.name))
请注意,这会改变原始的运动对象(更改为新的地图),还会添加false/true
而不是真实。