【问题标题】:How to recursively iterate over a JS object, while creating a new object, with a similar structure?如何在创建具有相似结构的新对象时递归迭代 JS 对象?
【发布时间】:2018-08-06 07:15:52
【问题描述】:

我正在尝试创建对象的“组合”,其中每个对象都有一些属性,以及对其他对象的引用(让我们将它们视为“子对象”);

此复合结构是从配置结构的配置对象创建的。例如:

const configObj = {

    baseSiteUrl: `https://example.com`,
    startUrl: `https://example.com/products`,
    type:'root',
    children: [
        {
            type: 'link',
            name: '.product_name_link',
            children: [
                {
                    type: 'data',
                    name: '.product_publisher'
                }

            ]
        }
    ]

}

我需要将这样的结构转换为对象实例的实际组合(我有“Link”和“Data”类,每个类都有不同的用途:Link 向该地址发送 HTTP 请求,Data 获取某个元素)。

到目前为止,我尝试过的只是一个荒谬的黑客行为。这是我的递归函数:

function createObjectsFromTree(object) {
    const classReference = getClassMap()[object.type];//Brings a reference to the appropriate class.

    if(object.type !== 'root'){
        object.actualObject = new classReference(object.name, object.children || null);//This is the hack: it just creates a property called "actualObject", on the original object. 
    }       

    if (!object.children) {
        return;
    }

    object.children.forEach((child) => {        

        createObjectsFromTree(child)
    })

}

 createObjectsFromTree(configObj);//Making the initial call

这是getClassMap函数:

 function getClassMap() {
    return {
        link: Link,
        root:Root,
        data: Data
    }

}

如您所见,我只是在修改原始配置对象,添加一个“actualObject”属性,该属性将一个实例保存到一个对象,并且这个过程会自我重复。

这显然是完全有缺陷的,只会导致问题,并使我的代码无法维护。

如何根据配置“蓝图”创建新的对象组合?

新对象在控制台中应该是这样的:

{

    baseSiteUrl: `https://example.com`,
    startUrl: `https://example.com/products`,
    type:'root',
    children: [
        Link{// "Link" is the class name                
            name: '.product_name_link',
            children: [
                Data{// "Data" is the class name                         
                    name: '.product_publisher'
                }

            ]
        }
    ]

}

任何想法将不胜感激!

【问题讨论】:

  • 请添加对函数的调用,作为想要的结果。这也有帮助:minimal reproducible example
  • 请添加getClassMap 可能还有其他缺失的功能。
  • 我已经添加了请求的项目
  • 除非你return递归调用你的函数的结果,否则不会发生太多事情。
  • torazaburo:好的,但是我该怎么做呢?我没有任何线索。想象一下,对于每次迭代,都需要在新对象上创建一个新项,同时保持原来的深度和索引。

标签: javascript recursion


【解决方案1】:

我试图让它尽可能短。 我假设你想实现这样的目标:

function createObjectsFromTree(object) {
  let Class = getClassMap()[object.type];
  return new Class(
    object.name,
    (object.children || []).map(createObjectsFromTree)
  );
}

这是JSFiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    • 2011-01-13
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    相关资源
    最近更新 更多