我对以下情况有疑问,因此,请检查以下对象数组:
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
}];
我想根据 名称 和 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”的对象的单独数组。
答案 0 :(得分:1)
使用array.filter
var nameArr = ...;
var col = ...;
var found = arrayQualityRated.filter(function() {
return name.indexOf(this.name) != -1 && this.col === col;
});
答案 1 :(得分:1)
我认为这不是一个简单的过滤器,因为预期结果会出现在三个不同的数组中。我会使用 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))