In the context of a web app, I have a server which sends or receives JSON strings based on the input from the client. On client consumption, these JSON strings are immediately converted into JavaScript objects where they will live out their lives as objects. These objects are not arrays; they represent complex, arbitrary data models, each property of which can have an arbitrary number of unique subproperties or objects.
var myView = {
name: 'root'
id: 'root_0'
children: {
child_1: {
arbitraryid: 'root_0_child_1',
type: 'Department',
name: 'Produce',
quadrant: 1,
children: {
child_1: {
arbitraryid: 'root_0_child_1_child_1',
type: 'Aisle',
number: 3,
length: 12,
children: { }
}
}
},
child_2: {
arbitraryid: 'root_0_child_2',
name: 'West',
type: 'Region',
children: {
child_1: {
arbitraryid: 'root_0_child_2_child_1',
name: 'Wegmans',
type: 'Store',
children: {
child_1: {
arbitraryid: 'root_0_child_2_child_1_child_1',
type: 'Department',
children: { }
}
}
}
}
}
}
};
When I build the JSON string server side, I guarantee that all objects will have 'children' and 'arbitraryid' properties; but everything else is dynamically generated and the properties and values are completely arbitrary.
If this were XML, I could use jQuery to var someChild = myView.find('#root_0_child_1_child_1')
. This would get me a jQuery object with the results of the find AND not only a reference to myView but a position from which to move omnidirectionally through the object: var someChild = myView.find('#root_0_child_1_child_1').parent()
.
Does a utility exist to solve this problem for native, JavaScript objects or is there a preferable way/methodology to do this? I'd like to avoid writing a bunch of this type of code to simply get at my property and then potentially loop again to update the parent object.
while (obj.hasOwnProperty('children')) {
for (var child in obj) {
//..etc, etc
}
}
Most of the SO questions I see on this subject deal with searching arrays, frequently with predictable data table style construction.
Mapping is possible, but these objects quickly become deep and that option seems little better than dumb looping.
Ideas?
Edit: rolling my own utility class.
I'm still exploring other libraries/utilities, but I wrote a generic helper class to do searches:
ObjectHelper
While useful, I think it illustrates some of the difficulty with getting at other jQuery-like functionality. Not only would I like to search, but I'd like to be able to crawl up/down the object property structure similarly to the way you can chain .parent().children().find() operators together. Doable, but complicated.