伙计们,我不怎么给这个话题。我无法将数据从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
,结果我得到了很多。以及很多重复性的动物类别。(如下图所示)
UPDATED:我要查找的输出是:-
animalCategory: [ 'cat', 'dog', 'iguana', 'fish']
那我该如何改变我的逻辑呢?还有其他方法可以做到吗?
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" }
]
}
]
// 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 {
if(animalCategory.indexOf(animal.category) === -1) {
animalCategory.push(animal.category);
}
}
});
});
// see result
animalCategory.forEach(function(animal) {
console.log(animal);
});
希望这对您有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句