递归地展开一个对象数组

3
我有一个对象数组..如何将多维对象数组扁平化为单维对象数组?
[{
    "name":"Locations",
    "children":[
        {
            "name":"U.S."
        },
        {
            "name":"Canada"
        },
        {
            "name":"London"
        }
    ]
},{
    "name":"Benefits",
    "children":[
        {
            "name":"U.S. Benefits",

            "children":[
                {
                    "name":"U.S. Benefits at a Glance"
                },
                {
                    "name":"U.S. Holiday Calendar"
                }
            ]
        },
        {
            "name":"London Benefits",
            "children":[
                {
                    "name":"London Benefits at a Glance"
                },
                {
                    "name":"London Holiday Calendar"
                }
            ]
        },
        {
            "name":"India Benefits",
            "children":[
                {
                    "name":"India Benefits at a Glance"
                },
                {
                    "name":"India Holiday Calendar"
                }
            ]
        }
    ]
}]

我需要所有子元素都在单维数组中与它们的父元素处于同一级别。任何帮助将不胜感激。

我会创建一个空数组来整理最终的列表。然后,我会编写一个递归算法,使用array.splice将所有子节点插入到最终列表中,并在下降过程中迭代子节点,从节点中删除任何'children'属性。当递归回溯时,也会删除这些属性。 - undefined
3
你期望的输出是什么样子? - undefined
3个回答

9
你可以使用reduce和扩展语法在没有lodash的情况下完成这个操作。你只需要对子元素使用递归即可。

const data = [{"name":"Locations","children":[{"name":"U.S."},{"name":"Canada"},{"name":"London"}]},{"name":"Benefits","children":[{"name":"U.S. Benefits","children":[{"name":"U.S. Benefits at a Glance"},{"name":"U.S. Holiday Calendar"}]},{"name":"London Benefits","children":[{"name":"London Benefits at a Glance"},{"name":"London Holiday Calendar"}]},{"name":"India Benefits","children":[{"name":"India Benefits at a Glance"},{"name":"India Holiday Calendar"}]}]}]

const flatten = data => {
  return data.reduce((r, { children, ...rest}) => {
    r.push(rest);
    if (children) r.push(...flatten(children));
    return r;
  }, [])
}

console.log(flatten(data))


3

@nenad-vracar修改的答案改为更具可重用性的样式:

const mock = [{"name":"Locations","children":[{"name":"U.S."},{"name":"Canada"},{"name":"London"}]},{"name":"Benefits","children":[{"name":"U.S. Benefits","children":[{"name":"U.S. Benefits at a Glance"},{"name":"U.S. Holiday Calendar"}]},{"name":"London Benefits","children":[{"name":"London Benefits at a Glance"},{"name":"London Holiday Calendar"}]},{"name":"India Benefits","children":[{"name":"India Benefits at a Glance"},{"name":"India Holiday Calendar"}]}]}];

const flatDeepByKey = (data, key) => {
  return data.reduce((prev, el) => {
    prev.push(el);
    if (el[key]) {
      prev.push(...flatDeepByKey(el[key], key))
    };
    return prev;
  }, [])
};

console.log(flatDeepByKey(mock, 'children'));


1

您可以使用辅助函数执行递归循环并将其附加到运行列表中。

注意: 如果要删除“根”虚拟节点,只需slice(1)数组即可。

var flattened = flattenTree({
  "name" : "root",            // Need a root entry, because the data is an array
  "children" : getData()      // Grab the data at the bottom
}, {
  nameKey : 'name',           // The name key; configurable option
  childrenKey : 'children'    // The children key; configurable option
});

console.log(flattened);       // Flattened data printed to the console

function flattenTree(tree, options) {
  options = options || {};
  var nameKey = options.nameKey || 'name';
  var childrenKey = options.childrenKey || 'children'
  var resultList = [];
  flattenTreeRecurse(tree, resultList, nameKey, childrenKey);
  return resultList;
}

/** @private -- Recursive inner-call */
function flattenTreeRecurse(tree, list, nameKey, childrenKey) {
  var entry = {};
  entry[nameKey] = tree[nameKey];
  list.push(entry);
  if (tree[childrenKey] && tree[childrenKey].length > 0) {
    tree[childrenKey].forEach(child => flattenTreeRecurse(child, list, nameKey, childrenKey));
  }
}

function getData() {
  return [{
    "name": "Locations",
    "children": [{
      "name": "U.S."
    }, {
      "name": "Canada"
    }, {
      "name": "London"
    }]
  }, {
    "name": "Benefits",
    "children": [{
        "name": "U.S. Benefits",

        "children": [{
          "name": "U.S. Benefits at a Glance"
        }, {
          "name": "U.S. Holiday Calendar"
        }]
      },
      {
        "name": "London Benefits",
        "children": [{
          "name": "London Benefits at a Glance"
        }, {
          "name": "London Holiday Calendar"
        }]
      },
      {
        "name": "India Benefits",
        "children": [{
          "name": "India Benefits at a Glance"
        }, {
          "name": "India Holiday Calendar"
        }]
      }
    ]
  }];
}
.as-console-wrapper { top: 0; max-height: 100% !important; }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接