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: { }
}
}
}
}
}
}
};
当我在服务器端构建JSON字符串时,我保证所有对象都具有“children”和“arbitraryid”属性;但其他所有内容都是动态生成的,属性和值完全任意。
如果这是XML,我可以使用jQuery来var someChild = myView.find('#root_0_child_1_child_1')
。这将让我得到一个jQuery对象,其中包含查找结果而且不仅是对myView的引用,还有一个位置,可在其中通过对象进行全向移动:var someChild = myView.find('#root_0_child_1_child_1').parent()
。
是否存在解决原生JavaScript对象这个问题的实用程序,或者是否有更好的方法/方法论来解决这个问题?我希望避免编写大量此类代码,以便简单地获取我的属性,然后可能再次循环以更新父对象。
while (obj.hasOwnProperty('children')) {
for (var child in obj) {
//..etc, etc
}
}
我看到大部分关于这个问题的SO问题都涉及搜索数组,经常是可预测的数据表格样式构建。
映射是可能的,但这些对象很快就会变得深层,这个选项似乎比愚蠢的循环好不了多少。
有什么想法吗?
编辑:自己编写实用程序类。
我仍在探索其他库/实用程序,但我编写了一个通用的辅助类来进行搜索:
虽然有用,但我认为它展示了访问其他类似jQuery功能的困难之处。我不仅想搜索,还想能够沿着对象属性结构向上/向下爬行,类似于您可以将.parent().children().find()操作符链接在一起的方式。可行,但复杂。