我想编写一个检查对象atrribute数组中是否包含关键字的函数。如果在该数组中找到了关键字,则应返回该对象。
我尝试了下面的代码,但没有用。我希望有人能告诉我这段代码做错了什么:)
我的目标是该函数:Projects.detectProjectByKeyword("brumi")
返回ImageObjects.DE.brumi
也许有更简单的方法可以实现目标?非常感谢您的帮助,因为我在这里呆了一个多星期:(
var ImageObjects = function() {
var DE = {
brumi : {
name:"Brummi-Werk",
keywords: ["brumi","auto", "LKWs", "lkws","lkw-werkstatt","die Brummis"]
},
medien : {
name: "medien",
keywords:["vier","nummer vier", "springer", "neue medien", "neue medien ag", "die neue medien ag"]
},
mautmaxe : {
name: "mau",
keywords:["fünf","nummer fünf", "mautmaxe", "maut", "currywust", "currywurst stand"]
}
};
return {
DE: DE
}
}();
function searchObj(obj, query) {
var data ='';
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] === "object") {
data = searchObj(obj[property], query);
if(data !='') return data;
}
else {
if (obj["keywords"].indexOf(query) >= 0) {
return obj;
}
else {
return null;
}
}
}
}
return data;
}
var Projects = function() {
function detectProjectByKeyword(project) {
var foundObject = null;
for (var x in ImageObjects.DE){
if ((searchObj(ImageObjects.DE[x], project))!=null){
foundObject = searchObj(ImageObjects.DE[x], project)
}
}
return foundObject;
}
return {
detectProjectByKeyword: detectProjectByKeyword
}
}();
最佳答案
如果结构从不改变,IE; ImageObjects.LANGUAGE.project.keywords
,就足够了:
function detectProjectByKeyword(keyword, obj, language) {
for(var a in obj[language]) {
if(obj[language].hasOwnProperty(a)) {
if(obj[language][a].keywords.indexOf(keyword) >= 0) return obj[language][a]
}
}
}
console.log(detectProjectByKeyword('brumi', ImageObjects, 'DE'));
console.log(detectProjectByKeyword('lkws', ImageObjects, 'DE'));
console.log(detectProjectByKeyword('mautmaxe', ImageObjects, 'DE'));
这是一个示例:https://jsfiddle.net/jorgthuijls/o2a01p6h/
关于javascript - 在javascript中遍历对象以查找嵌套属性并返回找到的对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43646044/