如何遍历JSON树

时间:2018-06-12 00:51:46

标签: javascript json tree

请将下面的JSON转换为对象数组。我在递归时非常糟糕,而且我整天都在挣扎。请帮助我们。

{
  "org_name":"paradise island",
  "daughters" : [
    {
      "org_name": "banana tree",
      "daughters": [
        {"org_name":"Yellow Banana"},
        {"org_name":"Brown Banana"}
      ]
    },
    {
      "org_name": "big banana tree",
      "daughters": [
        {"org_name":"green banana"},
        {"org_name":"yellow banana"},
        {
          "org_name": "Black banana",
          "daughters": [
            {"org_name": "red spider"}
          ]
        }
      ]
    }
  ]
}

我希望将其转换如下:

[
  {id:1, name:'paradise island', parent: null},
  {id:2, name:'Banana Tree', parent: 1},
  {id:3, name:'yellow banana', parent: 2}
]

订单无关紧要。重要的是根据父母对孩子的正确身份关系。我打算将id生成为UUID。但无论如何你都可以生成它。

2 个答案:

答案 0 :(得分:0)

看起来非常简单,只需为函数外部的未使用标识符声明一个变量,让函数将当前对象和数组推送,并在每个子函数上调用该函数,如果它们存在:

const input={"org_name":"paradise island","daughters":[{"org_name":"banana tree","daughters":[{"org_name":"Yellow Banana"},{"org_name":"Brown Banana"}]},{"org_name":"big banana tree","daughters":[{"org_name":"green banana"},{"org_name":"yellow banana"},{"org_name":"Black banana","daughters":[{"org_name":"red spider"}]}]}]};

let nextUnusedId = 0;
const addToArr = ({ org_name: name, daughters }, parent = null, addTo = []) => {
  const id = nextUnusedId++;
  addTo.push({ id, name, parent });
  if (daughters) daughters.forEach(daughter => addToArr(daughter, id, addTo));
  return addTo;
};
console.log(
  addToArr(input)
);

答案 1 :(得分:0)

感谢@CertainPerformance。这是我的最终解决方案



const uuidv4 = require('uuid/v4');

function serialize(payload) {

	return (function traverse(res, payload, parent) {

		var row = {}, uuid = '', prop;

		uuid = uuidv4()
		row.id = uuid
		row.name = payload["org_name"]
		row.parent = parent
		res.push(row);

		if(payload.hasOwnProperty('daughters')){
			payload["daughters"].forEach(function(daughter) {
				traverse(res, daughter, uuid)
			})
		}

		return res

	})(res = [], payload, parent = 'null')
}