如何使用 JavaScript/Prototype 1.7 递归搜索对象树并根据键/值返回匹配对象 [英] How do I recursively search an object tree and return the matching object based on a key/value using JavaScript/Prototype 1.7
问题描述
我有一些嵌套的对象数据,我想搜索它并根据 id 返回匹配的对象.
I've got some nested object data and I want to search it and return the matching object based on the id.
var data = [{id: 0, name: 'Template 0', subComponents:[
{id: 1, name: 'Template 1', subItems:[
{id: 2, name: 'Template 2', subComponents:[{id: 3, name: 'Template 3'}], subItems: [{id: 4, name: 'Template 4'}]}
]}
]}
];
所以我想做这样的事情
getObjectByKeyValue({id: 3})
让它返回
{id: 3, name: 'Template 3'}
因为我有子项和子组件,每个子组件都可以有子项,所以它必须是通用的.
It's sort of got to be done generically because I have subItems, AND subComponents which could each have children.
我使用 Prototype 1.7 尝试了这个,但没有运气 - 我认为这只是搜索一个数组,而不是带有子节点的树:
I tried this using Prototype 1.7 and no luck - I think this just searches an array, and not a tree with it's sub nodes:
data.find(function(s){return s.id == 4;})
提前致谢!!!!!!
推荐答案
我走了一条稍微不同的路线,将 findKey
方法设为对象原型:
I went a slightly different route and made the findKey
method an Object protype:
Object.prototype.findKey = function(keyObj) {
var p, key, val, tRet;
for (p in keyObj) {
if (keyObj.hasOwnProperty(p)) {
key = p;
val = keyObj[p];
}
}
for (p in this) {
if (p == key) {
if (this[p] == val) {
return this;
}
} else if (this[p] instanceof Object) {
if (this.hasOwnProperty(p)) {
tRet = this[p].findKey(keyObj);
if (tRet) { return tRet; }
}
}
}
return false;
};
您将直接在数据对象上调用,传入您要查找的键/值:
Which you would call directly on the data object, passing in the key/value you're looking for:
data.findKey({ id: 3 });
请注意,此函数允许您根据任意键查找对象:
Note that this function allows you to find an object based on any key:
data.findKey({ name: 'Template 0' });
查看示例 →(打开控制台查看结果)
See example → (open console to view result)
这篇关于如何使用 JavaScript/Prototype 1.7 递归搜索对象树并根据键/值返回匹配对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!