javascript - 对象内的递归

标签 javascript recursion data-structures

我正在尝试使用递归转换以下对象:

const objToConvert = {
 "article":[
   {
    "section@role":"Testing",
    "section":[
      {
        "title@id":"title test",
        "title":          {
          "content@id":"1",
          "content":"some simple content"
        }
      }
    ]
   }
  ]
};

到一个看起来像这样的对象:

const desiredObject = {
  type: "article",
  props: {
  },
  children: [
    {
      type: "section",
      props: {
        "section@role": "Testing"
      },
      children: {
        type: "title",
        props: {
          "title@id":"title test",
          "content@id":"1",
          "content":"some simple content"
        }
      }
    }
  ],
};

现在我对如何照顾 children 感到困惑。我尝试了不同的方法,但仍然无法使其正常工作。我有一个最初的解决方案,偶然使用数组而不是对象,但我需要它是一个对象。我真的迷失了..

jsfiddle:https://jsfiddle.net/7dmowrdj/3/

function nodeAttributes(obj) {

    let attributeList = {};

    for (var attrib in obj) {
      const item = obj[attrib];

      if (item && item.constructor === String && attrib.indexOf("@") !== -1) {
        const attribVals = attrib.split("@");
        const attribName = attribVals[1];

        attributeList[attribName] = item;

      }

      if (attrib == "annotate")
        attributeList[attrib] = item;

    }

    return attributeList;

  }

 function walkObject(obj, compStructure, objAttributes) {

    for (var property in obj) {
      if (obj.hasOwnProperty(property)) {
        if (typeof obj[property] == "object") {

          const curAttributes = nodeAttributes(obj[property]);

          const currentItem = {
            type: property,
            props: { ...objAttributes, ...curAttributes}
          };

         if (obj[property].constructor === Array) {              

              /* this work wont right */             
              //if (currentItem.children === undefined)
              //  currentItem.children = [];

              //this.walkObject(obj[property], currentItem.children, curAttributes);
              //compStructure = {...currentItem};

              walkObject(obj[property], compStructure, curAttributes);

          } else {

            walkObject(obj[property], compStructure, curAttributes);  
            debugger;

            if (!isNaN(parseInt(property)))
              compStructure = currentItem;

            debugger;

          }


        }
      }
    }
  }

  let compStructure = {};
  walkObject(objToConvert, compStructure, {});
  console.log(compStructure);

最佳答案

这是否符合您正在寻找的内容?它似乎可以处理给定的情况,但我可能会遗漏一些东西。

const objToConvert = {"article": [{"section": [{"title": {"content": "some simple content", "content@id": "1"}, "title@id": "title test"}], "section@role": "Testing"}]}

const convert = (obj) =>
  Object.keys(obj).reduce((curr, key) => obj[key] instanceof Array 
    ? Object.assign(curr, {type: key, props: curr.props, children: obj[key].map(convert)})
    : obj[key] instanceof Object
      ? Object.assign(curr, {type: key, props: Object.assign(curr.props, obj[key])})
      :  Object.assign(curr, {props: Object.assign(curr.props, {[key]: obj[key]})})
  , {props: {}})

 console.log(convert(objToConvert))

可能需要进行一些清理工作。如果不出意外的话,我不喜欢该函数中的所有 obj[key] 实例。但我把清理工作留给读者作为练习。 :-)

关于javascript - 对象内的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46590054/

相关文章:

javascript - 如何在动态添加的数组中具有不同的值

javascript - 如何一一获取目录下的文件链接并使用?

javascript - 使用递归和 yield 关键字提取嵌套列表的 Typescript 函数

c++ - 结构中的默认成员值或默认构造函数参数?

algorithm - 用于检查 O(1) 时间内元素数量是否相等的数据结构?

c# - 如何将此命名空间列表格式化为没有重复的结构化对象?

javascript - 在 HTML 中预加载图像

php - 如何将 JavaScript 变量传递给 PHP?

haskell - 无限生成汉明序列的最新技术

c++ - 为什么当将迭代器作为参数传递并在尾部位置递归时,后缀失败而前缀工作正常?