How to filter nested JSON object to return certain value using JavaScript ?

This example contains the information of 4 employees and we need to find the mobile number of the first employee then it can be done in the following manner.

employees[0].address.contact["mobile"]

To find the contact details of the second employee.

employees[1].address.contact["mobile"]

The dot operator is used for selecting the mobile from the contact field of the address field of the second employee.

<!DOCTYPE html>
<html>
<body>
	<h2 style="color: green;">
		GeeksForGeeks
	</h2>
	<script>
		var employees = [
		{
			"emp_id":101,
			"empname":"Ram",
			"salary":60000,
			"address" :
			{
				"street-no":20,
				"plot-no":121,
				"city":"pune",
				"contact" :
				{
					"landline" : 2292099,
					"mobile" : 8907632178
				}
			}
		},
		{
			"emp_id":102,
			"empname":"Shyam",
			"salary":50000,
			"address" :
			{
				"street-no":12,
				"plot-no":221,
				"city":"pune"
			}
		},
		{
			"emp_id":103,
			"empname":"Lakhan",
			"salary":40000,
			"address" :
			{
				"street-no":11,
				"plot-no":432,
				"city":"pune"
			}
		},
		{
			"emp_id":104,
			"empname":"Snigdha",
			"salary":60000,
			"address" :
			{
				"street-no":21,
				"plot-no":222,
				"city":"pune"
			}
		}]

		document.write("<b>" + "Employee Id : "
			+ "</b>" + employees[0].emp_id + "<br>");

		document.write("<b>" + "Employee Name : "
			+ "</b>" + employees[0].empname + "<br>");

		document.write("<b>" + "Employee Salary : "
			+ "</b>" + employees[0].salary + "<br>");

		document.write("<b>" + "Address -> "
			+ "Street Number : " + "</b>"
			+ employees[0].address["street-no"] + "<br>");

		document.write("<b>" + "Address -> "
			+ "Phone Number -> " + "</b>"
			+ "<b>" + "Mobile : " + "</b>"
			+ employees[0].address.contact["mobile"]
			+ "<br>");
	</script>
</body>

</html>

Output :

Leave a comment

Your email address will not be published. Required fields are marked *