How to retrieve a value by its key in jQuery
We can simply access the value directly from the object using the key. Here’s a basic example
<!DOCTYPE html>
<html>
<head>
<title>Retrieve Value by Key using jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<script>
// Example object with key-value pairs
var data = {
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4"
};
// Function to get the value by key
function getValueByKey(obj, key) {
return obj[key] !== undefined ? obj[key] : null; // Return the value or null if key is not found
}
$(document).ready(function() {
// Example usage
var keyToFind = "key3";
var value = getValueByKey(data, keyToFind);
if (value !== null) {
console.log("The value for the key '" + keyToFind + "' is: " + value);
} else {
console.log("No value found for the key: " + keyToFind);
}
});
</script>
</body>
</html>