The problem of converting array to object

there are multiple objects in an array, and each object contains a child array. Save the child array of each object in a new array

Mar.29,2021


var array = [{
  "name": "lishi",
  "friends": [{
    "name": "lishi1",
    "friends": [{
      "name": "lishi2",
      "friends": [{
        "name": "lishi3",
        "friends": []
      }]
    },
    {
      "name": "lishi4",
      "friends": []
    }]
  },
  {
    "name": "lishi5",
    "friends": []
  }]
},
{
  "name": "wanger",
  "friends": [{
    "name": "wangwu"
  }]
},
{
  "name": "zhangsan",
  "friends": []
}];

the subject does not post the specific structure of the data. Assuming that it is the above structure (there are multiple objects in an array, each object contains a sub-array), take out all the objects in the friends array and deal with them recursively.

var result = [];
function selectAllFriends(arr) {
  for (var i = 0; i < arr.length; iPP) {
    if (!arr[i].friends || arr[i].friends.length < 1) {
      continue;
    }
    selectAllFriends(arr[i].friends);
    result = result.concat(arr[i].friends);
  }

}
selectAllFriends(array);
for (var i = 0; i < result.length; iPP) {
  console.log(result[i]["name"]);
}
Menu