所以,伙计们,我不知道如何给这个话题提供一个话题。我无法将数据从 Object 数组复制到另一个新创建的数组。
例如,我想复制并创建一个新的array
,其中包含我数据库中每个人的所有动物类别。
people = [
{
name: "Person 1",
animals: [
{ category: "cat" },
{ category: "dog" },
{ category: "fish" }
]
},
{
name: "Person 2",
animals: [
{ category: "dog" },
{ category: "iguana" }
]
},
{
name: "Person 3",
animals: [
{ category: "cat" }
]
}
]
因此,我创建了一个新array
名称animalCategory
来保存每个可用的类别。
// declare new array to hold category of animals
let animalCategory = []
这是我想出的逻辑:-
// loop all person available
people.forEach(person => {
// go and loop inside animals array
person.animals.forEach(animal => {
// save new category of animals if animalCategory array is EMPTY
if(animalCategory.length === 0) {
animalCategory.push(animal.category)
}
// if NOT EMPTY, then
else {
// loop and check existing animal categories in animalCategory array
animalCategory.forEach(category => {
// check if MATCH?
if(category === animal.category) {
break // or just continue or will NOT BE SAVE
}
// if NOT MATCH, then
else {
// SAVE new category
animalCategory.push(animal.category)
}
})
}
})
})
// see result
console.log(animalCategory.length)
但不幸的是,结果我得到了一个非常大的数组animalCategory
。和很多重复的动物类别。(如下图所示)
更新:我想要寻求的输出是: -
animalCategory: [ 'cat', 'dog', 'iguana', 'fish']
那我应该如何改变我的逻辑呢?还有其他方法可以做到这一点吗?