我对以下情况有疑问,所以请检查以下对象数组:
let arrayQualityRated = [{
name: "Jande",
col: 4
}, {
name: "Good",
col: 4
}, {
name: "Good",
col: 4
}, {
name: "Bad",
col: 4
}, {
name: "Elmo",
col: 2
}, {
name: "Bad",
col: 2
}, {
name: "Tiago",
col: 3
}, {
name: "Bad",
col: 3
}];
我想做一些类似基于 name 和 col 键的过滤器。
但我需要动态执行,因此根据我的理解,根据以下数组查找键“name”:
let persons = ["Jande", "Elmo", "Tiago"]
我希望我已经澄清了我的疑问。我期待您的耐心和帮助! :)
我期望这样的输出:
[
{
name: "Jande",
col: 4
},
{
name: "Good",
col: 4
},
{
name: "Bad",
col: 4
},
{
name: "Good",
col: 4
}
],
[
{
name: "Elmo",
col: 2
},
{
name: "Bad",
col: 2
}
],
[
{
name: "Tiago",
col: 3
},
{
name: "Bad",
col: 3
}
]
简单地说,我想要一个基于字符串“person name”(基于数组“persons”)和“col”的单独对象数组。
最佳答案
我认为这不是一个简单的过滤器,因为结果预计在三个不同的数组中。我会使用 map() 然后使用 filter(),因为 col 值是动态的(在识别此人之前无法辨别)按名称)。
看看生成的数组 - 它具有您要求的结构。
let arrayQualityRated = [{
name: "Jande",
col: 4
}, {
name: "Good",
col: 4
}, {
name: "Good",
col: 4
}, {
name: "Bad",
col: 4
}, {
name: "Elmo",
col: 2
}, {
name: "Bad",
col: 2
}, {
name: "Tiago",
col: 3
}, {
name: "Bad",
col: 3
}];
let persons = ["Jande", "Elmo", "Tiago"]
const classifyArrayItems = (persons, arrayQualityRated) => {
// mapping the array, so it has all the persons
return persons.map(person => {
// first find the col number corresponding to the
// person in the array
const col = arrayQualityRated.find(e => e.name === person).col
// return all the objects that have the same
// col value
return arrayQualityRated.filter(e => e.col === col)
})
}
console.log(classifyArrayItems(persons, arrayQualityRated))
关于javascript - 如何按名称和列关联对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57792530/