Reputation: 5382
This is what my data looks like...
var data = [
{
name: 'Bart',
grade: 4,
teacher: 'Krabappel',
record: ['Set fire to skinner','Threw poop at Milhouse'],
friends: [
{
name: 'Milhouse',
grade: 4,
teacher: 'Krabappel',
record: ['Sang songs', 'Reads loudly'],
friends:
{
name: 'Martin',
grade: 4,
teacher: 'Krabappel',
record: 'NONE',
friends: 'NONE'
}
},
{
name: 'Nelson',
grade: 4,
teacher: 'Krabappel',
record: ['Burnt classroom','Stole skinners car','Beat up Milhouse'],
friends: 'NONE'
}
]
}
//{name: 'Lisa'},
//{name: 'Maggie'}
];
I'm trying to grab ALL instances of friends and log it.
function getFriends(data) {
data.map(function (n) {
var frands = n.friends; // works!
var fof = frands.friends; // does not work
console.log(frands);
console.log(fof);
});
}
getFriends(data);
How would I get all instances of friends including friends-of-friends?
Upvotes: 1
Views: 56
Reputation: 640
This calls for some recursion.
var allFriends = []; //global to store unique friend objects
for(var i = 0; i < data.length; i++){
if(data[i].friends != null){
getAll(data[i].friends);
}
}
function found(friend){
for(var i = 0; i < allFriends.length; i++){
if(allFriends[i].name == friend.name){
return true;
}
}
return false;
}
function getAll(friends){
if(friends != null){
for(var i = 0; i < friends.length; i++){
if(!found(friends[i])){
var friendcopy = friends[i];
if(friendcopy.friends != null){
delete friendcopy.friends;
getAll(friends[i].friends);
}
allFriends.push(friendcopy);
}
}
}
}
This will store all the unique friends found in the data array. The first function checks if the friend is already inside of the global variable allFriends
and if not then the recursive function will continue to scan indefinitely until all data elements are exhausted. When the recursion is complete, allFriends should contain all friend objects.
Although this type of function could become problematic if there is a very large amount of items in data
Upvotes: 1
Reputation: 4584
it's because more array is exist on it ,so use for loop will be ok
function getFriends(data) {
data.map(function (n) {
var frands = n.friends; // works!
for(var i =0;i <frands.length;i++){
var fof = frands[i].friends;
console.log(fof);
}
console.log(frands);
});
}
Upvotes: 1