Pergunta de entrevista da empresa A10 Networks

4. Please give a function which can print all node/child-node names of a json object in tree structured. EG: var tree = { node1:{ node2:"", node3:{ node4:"" } } } Print: ["node1", "node2", "node3", "node4"]

Resposta da entrevista

Sigiloso

7 de dez. de 2016

function printTree(tree){ var arr = []; function getChild(obj){ for(prop in obj){ // skip loop if the property is from prototype if (!obj.hasOwnProperty(prop)) continue; arr.push(prop); if(typeof obj[prop] === "object"){ getChild(obj[prop]); } } } getChild(tree); return arr; }