我试图找出给定的键是否存在于对象数组中。如果值键存在,那么我想返回 true 否则返回 false。
我从文本框中输入键,然后检查键是否存在于对象数组中,但我无法得到它。
这是我尝试过的
代码:
var obj = [{
"7364234":"hsjd",
"tom and jerry":"dsjdas",
"mickey mouse":"kfjskdsad",
"popeye the sailor man":"alkdsajd",
"the carribean":"kasjdsjad"
}]
var val = $("input[name='type_ahead_input']").val();
if (obj[val]) {
console.log('exists');
} else {
console.log('does not exist');
}
Run Code Online (Sandbox Code Playgroud)
如果我将输入作为the carribean对象数组中存在的' '给出,即使它在控制台中的输出也不存在。
我该如何解决这个问题?
您可以过滤对象数组并仅返回具有所需键的对象。然后,如果结果数组的长度大于零,则意味着存在具有该键的元素。
var obj = [{
"7364234":"hsjd",
"tom and jerry":"dsjdas",
"mickey mouse":"kfjskdsad",
"popeye the sailor man":"alkdsajd",
"the carribean":"kasjdsjad"
}];
var val = "the carribean";
var exists = obj.filter(function (o) {
return o.hasOwnProperty(val);
}).length > 0;
if (exists) {
console.log('exists');
} else {
console.log('does not exist');
}
Run Code Online (Sandbox Code Playgroud)
true如果数组包含具有所需键的对象,无论其值是undefined或 ,这都会返回null。
你可以typeof用来检查是否key存在
if (typeof obj[0][val] !== "undefined" ) {
console.log('exists');
} else {
console.log('does not exist');
}
Run Code Online (Sandbox Code Playgroud)
注意:有索引0,因为您正在检查的对象是数组的元素 0obj
这是一个小提琴:
if (typeof obj[0][val] !== "undefined" ) {
console.log('exists');
} else {
console.log('does not exist');
}
Run Code Online (Sandbox Code Playgroud)
正如下面 Cristy 所建议的,您也可以使用 obj[0][val] === undefined
你也可以:
var obj = [{
"7364234":"hsjd",
"tom and jerry":"dsjdas",
"mickey mouse":"kfjskdsad",
"popeye the sailor man":"alkdsajd",
"the carribean":"kasjdsjad"
}];
var val = "7364234";
if ( val in obj[0] ) {
console.log('exists');
} else {
console.log('does not exist');
}
Run Code Online (Sandbox Code Playgroud)
我建议使用Array.some()来了解某个键是否存在并 Array.find()获取找到的键的值,以及一些最新的语法:
let arr = [{"foo": 1}, {"bar":2}];
function isKeyInArray(array, key) {
return array.some(obj => obj.hasOwnProperty(key));
}
function getValueFromKeyInArray(array, key) {
return array.find(obj => obj[key])?.[key];
}
console.log(isKeyInArray(arr, "foo"), isKeyInArray(arr, "bar"), isKeyInArray(arr, "baz"));
console.log(getValueFromKeyInArray(arr, "foo"), getValueFromKeyInArray(arr, "bar"), getValueFromKeyInArray(arr, "baz"));Run Code Online (Sandbox Code Playgroud)