Skip to content

Instantly share code, notes, and snippets.

@yashasvi9199
Created June 15, 2023 13:54
Show Gist options
  • Save yashasvi9199/674dca7fc07acd929edd4dd4c46b2e52 to your computer and use it in GitHub Desktop.
Save yashasvi9199/674dca7fc07acd929edd4dd4c46b2e52 to your computer and use it in GitHub Desktop.
Use JSON object in simplofied way to find if the object have required properties using hasOwn function of jquery
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
</head>
<body>
<form>
<input type="text" placeholder="Enter First Name" id="fname" readonly>
</br>
</br>
<input type="text" placeholder="Enter Last Name" id="lname" readonly>
</br>
</br>
<select id="state">
<option value="">--Select State--</option>
<option value="Rajasthan">Rajasthan</option>
</select>
</form>
<script>
$(document).ready(function() {
let text = '{ "employees" : { "firstName":"John" , "lastName":"Doe" }, "location" : ""}';
const obj = JSON.parse(text);
if (Object.hasOwn(obj.employees, "firstName")) {
$("#fname").val(obj.employees.firstName)
$("#fname").prop('readonly', false);
console.log(obj.employees.firstName);
} else {
console.log("No First name found");
}
if (Object.hasOwn(obj.employees, "lastName")) {
$("#lname").val(obj.employees.lastName)
console.log(obj.employees.lastName);
} else {
console.log("No Last name found");
}
if (!Object.hasOwn(obj, "state")) {
$("#state").prop("disabled", true);
} else {
$("select#state option[value='" + obj.state + "']").attr("selected", true);
$("#state").prop("disabled", false);
}
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment