How Check Key Exist in Object Using Javascript And Javascript Date Object

1. How to check particular key exist in Object Javascript

Javascript Objects are collection of properties. It is being defined as pairs of key(name) and value {key:value}.

We can check if a particular key exists are not in a certain object and we can list all the key values of a Object. There are different ways we can check specific keys.

Ojbect.keys() is the method we can use in Javascript.Here we can see all keys contained in Object.

Example index.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="app"></div>
    <div id="result"></div>
</body>
</html>

index.js


// Write Javascript code!
const appDiv = document.getElementById('app');
appDiv.innerHTML = `

Find or Display Keys in Javascript Object

`; var blogObject = { "posts": [ { "id": 1, "title": "web Server", "author": "Williams" } ], "profile": { "name": "Williams" }, "data type" : typeof this, displayDataType: function() { return (this["data type"]); } } //Keys in Object result.innerHTML = Object.keys(blogObject);

To get all key values , simply pass object to javascript’s Object.keys(blogObject), the result will be :

Output


var ResultObj = Object.keys(blogObject);

console.log(ResultObj); //['posts','profile','data type','displayDataType']

To Check if a “Specific Key” exists in a Object

we can check a “specific key” exist within a javascript object, we use Object.prototype.hasOwnProperty() . To use it you just pass in a string format with the name of the key for which you are searching. This method will returns the boolean true or false value based on the match.See the below


var result = blogObject.hasOwnProperty('profile');
console.lof(result) 

//Output : 
true

Click Here For Code

2. Date Object in Javascript

In Javascrirpt Date is a type of object, we can create Date object using new Date().

There are different way to create date objects.

  • var dateObj = new Date();

  • var dateObj = new Date(milliseconds);

  • var dateObj = new Date(dateString);

  • var dateObj = new Date(year, month, day, hours, minutes, seconds, milliseconds);

We can convert in different format, some of them are

var dateObj = new Date(1542009908774); //milliseconds

dateObj.toLocaleString()     // 11/12/2018, 1:35:08 PM
dateObj.toLocaleDateString() // "11/12/2018"
dateObj.toDateString()       // "Mon Nov 12 2018"
dateObj.toTimeString()       // "13:35:08 GMT+0530 (India Standard Time)"
dateObj.toLocaleTimeString() // "1:35:08 PM"

Leave a Reply

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