如何检查如果键存在于一系列键值数组



我有一个像

[
{Key: 'FName', Value: 'John'},
{Key: 'LName', Value: 'Doe'},
{Key: 'Age', Value: '30'},
{Key: 'Person', Value: 'true'}
]

如何检查Person作为钥匙存在吗?

解决方案1

您可以使用<Array>.some

我还让函数接受你正在搜索的键和你正在寻找的值

const arr = [
{Key: 'FName', Value: 'John'},
{Key: 'LName', Value: 'Doe'},
{Key: 'Age', Value: '30'},
{Key: 'Person', Value: 'true'}
];


function isValueInsideField(arr, fieldName, value){
return arr.some(e => e[fieldName] === value);
}
console.log(isValueInsideField(arr, 'Key', 'Person'))
console.log(isValueInsideField(arr, 'Key', '123'))

<标题>

解决方案2 h1> 果你想从数组 中检索另一个值

const arr = [
{Key: 'FName', Value: 'John'},
{Key: 'LName', Value: 'Doe', someKey:false},
{Key: 'Age', Value: '30'},
{Key: 'Person', Value: 'true'}
];


function retriveValueIfKeyExists(arr, keyFieldName, value, valueFieldName){
// nullish concealing operator to return value even if it is falsy
// you can change it with || operator  but this might lead to un wanted results
// if the value is 0 or the boolean value false
return arr.filter(e => e[keyFieldName] === value)[0]?.[valueFieldName] ?? null;
}
console.log(retriveValueIfKeyExists(arr, 'Key', 'Person', 'Value'))
console.log(retriveValueIfKeyExists(arr, 'Key', 'LName', 'someKey'))
console.log(retriveValueIfKeyExists(arr, 'Key', '123'))

有一种方法:

const vals = [
{Key: 'FName', Value: 'John'},
{Key: 'LName', Value: 'Doe'},
{Key: 'Age', Value: '30'},
{Key: 'Person', Value: 'true'}
];
const personExists = () => vals.filter(x => x.Key === 'Person').length > 0;
console.log(personExists());

可以有多种方法:第三个也会返回值

const list = [
{Key: 'FName', Value: 'John'},
{Key: 'LName', Value: 'Doe'},
{Key: 'Age', Value: '30'},
{Key: 'Person', Value: 'true'}
];
function checkKeyClassical(key, list) {
for (let i = 0; i < list.length; i++) {
if (list[i].Key === key) {
return true;
}
}
return false;
}
function checkKeyOnlyExistence(key, list) {
return list.some(item => item.Key === key);
}
function checkKeyWithValue(key, list) {
let result = list.find(item => item.Key === key);
return result ? result.Value : false;
}
console.log(checkKeyClassical('FName', list)); // true
console.log(checkKeyOnlyExistence('FName', list)); // true
console.log(checkKeyWithValue('FName', list)); // John
console.log(checkKeyClassical('NOT_EXISTS', list)); // false
console.log(checkKeyOnlyExistence('NOT_EXISTS', list)); // false
console.log(checkKeyWithValue('NOT_EXISTS', list)); // false

相关内容

  • 没有找到相关文章