在对象中,我在多个实例中有相同的键,但值不同,如" string" /"对象" - 如何找到价值并为不同的任务创造条件..?
这是我的对象并尝试:
var obj = {
"Home":"Home link",
"Assignments":"Assignments link",
"Explorer":"Explorer link",
"Assignments":{
"Projects":"Projects sub string",
"Background Jobs":"Background sub string",
"Workflow Engine Queue":"Workflow Engine Queue sub string",
"Filter Engine Queue":"Filter Engine Queue sub string",
"Quotes":"Quotes sub string",
"Issues":"Issues sub string"
},
"Explorer":{
"Term Databases":"Term Databases sub string",
"Translation Memories":"Translation Memories sub string",
"Personal Preferences":"Personal Preferences sub string",
"Manage Locale":"Manage Locale sub string"
}
}
var objetProcess = function(){
$.each(obj, function(key, value){
console.log(key,$.type(value));
})
}
objetProcess();
我希望循环整个对象并找到值为" string"或"对象" - 并相应地设置任务。
答案 0 :(得分:3)
单个对象中不能有两个同名的键。在上面的示例中,Explorer和Assignments键始终是对象,因为设置字符串值的语句后跟另一个设置对象值的语句。
最简单的方法是用其他东西替换密钥名称,或者如果您尝试构建类似菜单层次结构的东西,则需要创建更复杂的数据结构来保存您的信息。想到这样的事情 -
var menu = [{label: "Home", url: "link"},
{label: "Assignments", url: "link",
children: [{label: "Foo", url: "link"}, {label: "Bar", url: "link"}]
},
{label: "Explorer", url: "link",
children: [{label: "Zac", url: "link"}, {label: "Cal", url: "link"}, {label: "Too", url: "link"}]
}
];
答案 1 :(得分:0)
您可以使用if
中的objetProcess
条件执行此操作,如下所示:
var objetProcess = function(){
$.each(obj, function(key, value){
if ($.type(value) === 'string') {
console.log('string task');
} else if ($.type(value) === 'object') {
console.log('object task');
}
})
}