根据给定的限制,按维度迭代对象数组

Iterate array of objects by dimension, based on given limit

我有一个包含建议用户的多维对象数组。 同样,每个建议的用户都有一些建议的用户等等。

在我正在构建的应用程序中,我 select 一个用户(我们称他为 'Steve')并希望接收一定数量的与该用户相关的用户(通过获取建议) .数据都在那里,我只需要找到一种有意义的方法来迭代它。

为了简化,我构建了一个包含一些示例数据的数组,其中每个用户都有两个建议用户:

// Suggested users of my initially selected user (Steve)
let suggested_users_based_on_steve = [
    {
        name: 'A',
        suggested: [
            {
                name: 'A1',
                suggested: [
                    { name: 'A1A1' },
                    { name: 'A1A2' }
                ]
            },
            {
                name: 'A2',
                suggested: [
                    { name: 'A2A1' },
                    { name: 'A2A2' }
                ]
            }
        ]
    },
    {
        name: 'B',
        suggested: [
            {
                name: 'B1',
                suggested: [
                    { name: 'B1B1' },
                    { name: 'B1B2' }
                ]
            },
            {
                name: 'B2',
                suggested: [
                    { name: 'B2B1' },
                    { name: 'B2B2' }
                ]
            }
        ]
    }
];

请注意,推荐用户数量不固定。每个用户都可以拥有无​​限数量的推荐用户。此外,逐层迭代以获得 'best' 和最相关的结果/用户也很重要。初始用户与 A 和 B 的联系比与 A1A1 和 A1A2 的联系更多。

我正在努力寻找嵌套 for...of 循环的正确组合。有什么推荐的方法吗?

提前致谢!

let suggested_users_based_on_steve = [
  {
    name: 'A',
    suggested: [
      {
        name: 'A1',
        suggested: [
          { name: 'A1A1' },
          { name: 'A1A2' }
        ]
      },
      {
        name: 'A2',
        suggested: [
          { name: 'A2A1' },
          { name: 'A2A2' }
        ]
      }
    ]
  },
  {
    name: 'B',
    suggested: [
      {
        name: 'B1',
        suggested: [
          { name: 'B1B1' },
          { name: 'B1B2' }
        ]
      },
      {
        name: 'B2',
        suggested: [
          { name: 'B2B1' },
          { name: 'B2B2' }
        ]
      }
    ]
  }
];

function test(arr, result = []) {
  for (let user of arr.values()) {
    result.push(user);
    if (result.length === 7) return result;
  }
  var next = arr.reduce(function (all, user) {
    return all.concat(user.suggested || []);
  }, []);
  if (next.length === 0) return result;
  return test(next, result);
}

test(suggested_users_based_on_steve);