在javascript中递归地从数组中提取值
Extract value from array recursively in javascript
我想递归地提取这个结构中的文件。我已经完成了第一层,但不能继续进行。
var DirectoryTree = {
dir: 'project1',
files: [
'proj.config', {
dir: 'src',
files: [
'name.htm',
'dept.htm',
'salary.htm', {
dir: 'scripts',
files: [
'name.js',
'dept.js',
'salary.js'
]
}
]
}, {
dir: 'project2',
files: [
'proj.config', {
dir: 'src',
files: [
'name.htm',
'dept.htm',
'salary.htm', {
dir: 'scripts',
files: [
'name.js',
'dept.js',
'salary.js'
]
}
]
}
]
}
]
};
下面是我到现在为止的代码。我被困在这里了。你能帮我拿到下一级的数据吗?
function listFiles(dirTree, subFolder){
var fList=[];
if(dirTree.files){
for (var i=0;i<dirTree.files.length;i++){
if(typeof dirTree.files[i] === 'string'){
fList.push(dirTree.files[i]);
}
}
}
if(dirTree.dir){
return(listFiles(dirTree.dir, subFolder));
}
return fList;
}
您可以递归地执行此操作,如下所示
function getFiles(currentObject, result) {
var type = Object.prototype.toString.call(currentObject),
idx;
if (type === "[object Object]") {
for (idx in currentObject) {
if (currentObject.hasOwnProperty(idx) && idx === "files") {
currentObject[idx].forEach(function(object) {
getFiles(object, result);
});
}
}
} else if (type === "[object Array]") {
currentObject.forEach(function(object) {
getFiles(object, result);
});
} else if (type === "[object String]") {
result.push(currentObject);
}
return result;
}
console.log(getFiles(DirectoryTree, []))
[ 'proj.config',
'name.htm',
'dept.htm',
'salary.htm',
'name.js',
'dept.js',
'salary.js',
'proj.config',
'name.htm',
'dept.htm',
'salary.htm',
'name.js',
'dept.js',
'salary.js' ]
我今天回答了一个类似的问题,并使用几个下划线函数解决了它。
您的示例的格式非常奇怪,但我再次建议对这种类型的读取使用递归函数:
function recursiveFuntion(collection){
collection.forEach(function(model) {
//console.log(model.files); --> Or do whatever you need
if(model.files.length > 0){
recursiveFunction(model);
};
});
};
recursiveFuntion(DirectoryTree.files);
递归函数的好处是它是动态的。
由于您使用的不是数组而是对象,因此需要自定义此代码。
但这是基本原则。
相关文章:
- Regex提取URL返回数组的一部分;未定义”;
- 如何从合并的结果集中提取数组
- 如何从数组中提取对象
- 从多维数组javascript中提取特定值
- 从数组中提取特定信息
- 使用JavaScript在Json中提取时,将数组的元素转换为String
- 正在复制数组并提取
- 在Jquery中从JSON中提取数组值
- 如何将json文件中的数据提取到对象数组中,并在两个控制器之间共享
- 使用从forEach循环中提取的国家代码从数组中获取国家名称
- 如何在javascript中使用localStorage从数组中存储和提取数据
- 循环遍历数字和字母数组并仅提取数字
- 如何从..中提取信息..我称之为数组
- 如何从生成的JSON数组中提取JSON对象
- 在jquery中使用.split并从数组中提取第一个项
- 在提取dom对象后,无法将每个名为tab的元素推送到数组中
- 使用jsRender,如何使用有序位置以外的东西从数组中提取特定项
- 创建新的javascript数组,从对象属性中提取数据
- 从SQL中提取一个表来创建javascript数组
- Javascript数组提取重复到新的数组