访问数组中属性值的属性值

Access property values of properties values in arrays

本文关键字:属性 数组 访问      更新时间:2024-03-17

这就是我的数据的样子。。。

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'} 
];

我正在尝试抓取所有朋友的实例并将其记录下来。

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);

我该如何获取朋友的所有实例,包括朋友的朋友?

这是因为上面有更多的数组,所以使用for循环就可以了

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);
    });
}

这需要一些递归。

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);
          }
       }
   }
}

这将存储在数据数组中找到的所有唯一好友。第一个函数检查友元是否已经在全局变量allFriends内,如果不是,则递归函数将无限期地继续扫描,直到耗尽所有数据元素。当递归完成时,allFriends应该包含所有的Friends对象。

尽管如果data 中有大量项目,这种类型的函数可能会出现问题