我有点谜题。我有所有奖项的数组1
array1 = [
{
"finished": 1,
"awardName": "The beginning",
"description": "Complete one excersise",
"difficulty": "easy",
"awarded": false
},
{
"finished": 5,
"awardName": "Five of a kind",
"description": "Complete five excersises",
"difficulty": "medium",
"awarded": false
}, ... ]`
和获奖的阵列2。
[
{
"award": "Five of a kind"
},
{
"award": "The beginning"
},
{
"award": "firstTimeLogin"
}
]
我想要做的是比较两个数组中的awardNames
,如果有同名的奖励,请将对象awarded
更改为true
。它看起来应该是这样的,this.array1[indexOfSecondArrayContainingThatAwardname].awarded = true
。我希望这是可能的,因为我还没有javascript的问题。谢谢!
答案 0 :(得分:2)
尝试使用findIndex()
:
const array1 = [{
"finished": 1,
"awardName": "The beginning",
"description": "Complete one excersise",
"difficulty": "easy",
"awarded": false
},
{
"finished": 5,
"awardName": "Five of a kind",
"description": "Complete five excersises",
"difficulty": "medium",
"awarded": false
}
];
const array2 = [{
"award": "Five of a kind"
},
{
"award": "The beginning"
},
{
"award": "firstTimeLogin"
}
];
for (const { award } of array2) {
const idx = array1.findIndex(i => i.awardName === award);
if (idx !== -1)
array1[idx].awarded = true;
}
console.log(array1);

答案 1 :(得分:1)
与forEach和map一起使用。
let array1 = [{
"finished": 1,
"awardName": "The beginning",
"description": "Complete one excersise",
"difficulty": "easy",
"awarded": false
},
{
"finished": 5,
"awardName": "Five of a kind",
"description": "Complete five excersises",
"difficulty": "medium",
"awarded": false
}
]
const array2 = [{
"award": "Five of a kind"
},
{
"award": "The beginning"
},
{
"award": "firstTimeLogin"
}
]
array2.forEach(award2=>{
array1 = array1.map(award1=>{
if(award2.award === award1.awardName){
award1.awarded = true;
}
return award1;
})
});
console.log(array1);

答案 2 :(得分:0)
您可以使用map和filter来链接抛出数组并返回所需的结果
var array1 = [
{
"finished": 1,
"awardName": "The beginning",
"description": "Complete one excersise",
"difficulty": "easy",
"awarded": false
},
{
"finished": 5,
"awardName": "Five of a kind",
"description": "Complete five excersises",
"difficulty": "medium",
"awarded": false
}
]
var array2 = [
{
"award": "Five of a kind"
},
{
"award": "The beginning"
},
{
"award": "firstTimeLogin"
}
]
array1.map(ele =>{
if (array2.filter(ele2 => ele.awardName === ele2.award).length > 0) ele.awarded = true;
});
console.log(array1);

答案 3 :(得分:0)
您可以使用哈希表并使用array2
进行设置,并使用array1``进行检查。
var array1 = [{ finished: 1, awardName: "The beginning", description: "Complete one excersise", difficulty: "easy", awarded: false }, { finished: 5, awardName: "Five of a kind", description: "Complete five excersises", difficulty: "medium", awarded: false }],
array2 = [{ award: "Five of a kind" }, { award: "The beginning" }, { award: "firstTimeLogin" }],
map = Object.create(null);
array2.forEach(({ award }) => map[award] = true);
array1.forEach(o => map[o.awardName] && (o.awarded = true));
console.log(array1);