首页 > 解决方案 > 从多级嵌套对象中动态提取相同的对象名称

问题描述

我想知道从多级嵌套对象中提取相同命名对象的最佳方法是什么。

我目前有一个看起来像这样的对象,我想从中提取parentLocationCluster对象。

 const foo = {
  id: '1',
  name: 'boo',
  parentLocationCluster: {
    id: 1,
    name: 'foo',
    parentLocationCluster: {
      id: 2,
      name: 'fii',
      parentLocationCLuster: {
        id: 3,
        name: 'faa',
      },
    },
  },
};

现在我可以if像这样嵌套语句:

const { parentLocationCluster } = foo;
if(parentLocationCluster) {
//do something
if(parentLocationCluster.parentLocationCluster) {
  //do something
 }
}

但我觉得这非常低效(这就是我目前正在做的事情)。此外,对象可以随嵌套的 parentLocationCluster 对象的数量而变化,即一个对象可以包含 10 个级别的 parentLocationCluster。

最好的方法是什么?

标签: javascriptreactjs

解决方案


下面的代码片段递归地访问所有嵌套的集群到任何深度,并对它们做一些事情。

const foo = {
  id: '1',
  name: 'boo',
  parentLocationCluster: {
    id: 1,
    name: 'foo',
    parentLocationCluster: {
      id: 2,
      name: 'fii',
      parentLocationCluster: {
        id: 3,
        name: 'faa',
      },
    },
  },
};

function readCluster(obj) {
  const cluster = obj.parentLocationCluster
  if (cluster) {
    // Do something
    console.log(cluster.name)
    readCluster(cluster)
  } else
    return;
}

readCluster(foo);


推荐阅读