gpt4 book ai didi

javascript - 在javascript中遍历对象寻找嵌套属性并返回找到的对象

转载 作者:行者123 更新时间:2023-11-30 15:21:36 24 4
gpt4 key购买 nike

我想编写一个函数来检查关键字是否包含在对象属性数组中。如果在该数组中找到关键字,它应该返回该对象。

我试过下面的代码,但它不起作用。我希望有聪明的人可以告诉我我在这段代码中做错了什么:)

我的目标是函数: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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com