我正在试图找出给定的键是否存在于对象数组中。如果值键存在,那么我想返回true else。
我从文本框输入键,然后检查该键是否存在于对象数组中,但无法得到。
这是我尝试过的
代码:
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');
}如果我以'the carribean‘的形式提供输入,它存在于对象数组中,即使它输出在控制台中也不存在。
我怎么解决这个问题?
发布于 2018-01-20 13:58:55
您可以使用typeof检查key是否存在。
if (typeof obj[0][val] !== "undefined" ) {
console.log('exists');
} else {
console.log('does not exist');
}注意:有索引0,因为您正在检查的对象是数组obj的元素0。
这里有一把小提琴:
var obj = [{
"7364234":"hsjd",
"tom and jerry":"dsjdas",
"mickey mouse":"kfjskdsad",
"popeye the sailor man":"alkdsajd",
"the carribean":"kasjdsjad"
}];
if ( typeof obj[0]["the carribean"] !== 'undefined' ) {
console.log('exists');
} else {
console.log('does not exist');
}
如下所示,您也可以使用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');
}发布于 2018-01-20 14:05:53
您可以筛选对象数组,并只返回具有所需键的对象。如果结果数组的长度大于零,则意味着存在具有该键的元素。
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');
}如果数组包含具有所需键的对象,则将返回true,而不管其值是undefined还是null。
发布于 2022-01-13 17:22:47
我建议使用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"));https://stackoverflow.com/questions/48356971
复制相似问题