Reputation: 347
This process, traversing a Javascript object is causing an infinite loop. The same code seems to work if I call it on initialize instead of on the key up event...Thanks for any help!
<form>
<input id="searchBox" name="searchText" placeholder="Search" onkeyup="search()">
</form>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var searchText = ""
function search(){
searchText = document.getElementById('searchBox').value;
traverse(jsonData,process);
}
//traverse JSON object
function traverse(json,func) {
for (var i in json) {
func.apply(this,[i,json[i]]);
if (json[i] !== null && typeof(json[i])=="object") {
console.log("STEP IN");
traverse(json[i],func);
}
}
}
Upvotes: 1
Views: 1375
Reputation:
You could easily cause an infinite loop if the object is recursive:
jsonData = {};
jsonData.x = jsonData;
You could use weakmaps to keep track of which nodes you have visited and avoid the recursion.
var map = new WeakMap();
function traverse(data, func) {
if (data != null || "object" !== typeof data || map.get(data)) { return; }
map.set(data, true);
for (var i in data) {
func.apply(this, [i, data[i]]);
console.log("STEP IN");
traverse(data[i], func);
}
}
}
Upvotes: 2