There is json data to display them in the jquery plugin tree generator, you need to translate it into a format with an indication of id and parent id, and in almost all json visualization plugins this format is perceived by the standard.

There is such a data object

{ "product": { "recommended": { "article": "blabla", "description": [] }, "article": [], "description": [], "manufacturer": [], "images": { "custom": [], "commercial": [] }, "reviews": [] } } 

At the exit you need to get

 [{ id: 0, parent: 0, key: "product" }, { id: 1, parent: 0, key: "recommended" }, { id: 2, parent: 1, key: "article", value: "blabla" }, ...] 

There were no suitable libraries for working with wood or functions on the network.

  • I do not see the similarity between input and output. - Jean-Claude
  • nesting, how is the similarity? id = iteration, value! = object - aliokero
  • one
    and finally it dawned on me ... Well, everything is pretty easy here. Now I will write the answer - Michael

1 answer 1

 var obj = { objects: { lol: "kek", jack: "chebureck" }, hz: { obj1: "1", objM: { obj2: "2", obj3: "3" } } }; //^^это тестовый объект var i = 1,//id первого класса tree = function(obj, parent) { var req = []; for (var key in obj) {//переор по прямым потомкам объекта var tmp = { id: i, parent: parent !== undefined ? parent : 0,//задаёт id родителя(если его нет, то 0, т.к. сам obj тоже счтается, но вы можете и -1 поставить) key: key }, c = obj[key].constructor === Object;//так более быстро и надёжно проверять, чем typeof i++; if (!c) tmp.value = obj[key];//если в значении- не объект, то мы просто добавляем в вывод value req.push(tmp); if (c)//если объект, то начинается рекурсия, первый аргумент- объект из value, второе- id его родителя(текущего объекта) tree(obj[key], tmp.id).forEach(function(el) { req.push(el); }); } return req; } console.log(tree(obj)); 

  • one
    Michael, thanks! - aliokero