我有对象的数组。数组中的每个对象都有一个ID和一个项属性,它是包含其他对象的数组。我需要能够找到在一个阵列按id的元素。下面是我迄今所做的一个样本,但递归函数总是返回undefined。
I have an array of objects. Every object in the array has an id and an item property that is an array containing other object. I need to be able to find an element in an array by id. Here is a sample of what I have done so far, but the recursive function is always returning undefined.
我怎么能退出的功能和回报的项目时,我已经调用的函数递归几次?
How can I quit the function and return the item when I have called the function recursively several times?
$(function () {
var treeDataSource = [{
id: 1,
Name: "Test1",
items: [{
id: 2,
Name: "Test2",
items: [{
id: 3,
Name: "Test3"
}]
}]
}];
var getSubMenuItem = function (subMenuItems, id) {
if (subMenuItems && subMenuItems.length > 0) {
for (var i = 0; i < subMenuItems.length; i++) {
var item;
if (subMenuItems[i].Id == id) {
item = subMenuItems[i];
return item;
};
getSubMenuItem(subMenuItems[i].items, id);
};
};
};
var searchedItem = getSubMenuItem(treeDataSource, 3);
alert(searchedItem.id);
});
的jsfiddle
推荐答案
您应该替换
getSubMenuItem(subMenuItems[i].items, id);
与
var found = getSubMenuItem(subMenuItems[i].items, id);
if (found) return found;
为了返回元素的时候才发现。
in order to return the element when it is found.
和小心的属性名,JavaScript是大小写敏感的,所以你也必须更换
And be careful with the name of the properties, javascript is case sensitive, so you must also replace
if (subMenuItems[i].Id == id) {
与
if (subMenuItems[i].id == id) {
示范
决赛(清洗)code:
Final (cleaned) code :
var getSubMenuItem = function (subMenuItems, id) {
if (subMenuItems) {
for (var i = 0; i < subMenuItems.length; i++) {
if (subMenuItems[i].id == id) {
return subMenuItems[i];
}
var found = getSubMenuItem(subMenuItems[i].items, id);
if (found) return found;
}
}
};
相关推荐
最新文章