Object.key() in JavaScriptIn JavaScript, Object.keys() is a built-in method that returns an array of a given object's own enumerable property names, in the same order as a for...in loop would iterate them. Example:-Here's an example: Output [ 'name', 'age', 'job' ] In this example, the Object.keys() method is used to return an array of the myObject object's property names. The resulting array contains the strings 'name', 'age', and 'job'. Note that the method only returns the object's own enumerable properties, which means that the properties that are directly defined on the object are not properties inherited from its prototype chain. To include all properties, enumerable and non-enumerable, you can use Object.getOwnPropertyNames() method instead. Example:-Here's another example of using Object.keys() to iterate over an object's properties: Output: The output of this code would be: name: John age: 30 job: Developer In this example, we first get an array of the myObject object's property names using Object.keys(). After that, we use for loop to iterate over the keys array and log each property name and its corresponding value to the console. Note that the order of the properties in the output may not necessarily match the order in which they were defined in the object literal. Example:-This is another example that demonstrates how to use Object.keys() to manipulate an object's properties: Output { name: 'John', age: 31, location: 'USA' } name: John age: 31 job: undefined In this example, we start by getting an array of the myObject object's property names using Object.keys(). After that, we add a new property (location) to the object, delete an existing property (job), and update an existing property (age). We then log the updated object to the console. Example:-This example shows how to use Object.keys() to create a new object that contains only certain properties of an existing object: Output { name: 'John', age: 30 } In this example, we start by defining an array selectedKeys that contains the names of the properties we want to include in the new object. After that, we use Object.keys() to get an array of all the property names in myObject. We use the Array.filter() method to remove any property names that are not included in selectedKeys. After that, we use the Array.reduce() method to create a new object containing only the selected properties. The reduce() method takes an initial value of an empty object ({}) and a callback function that adds each selected property to the object. Here are some more important points to note about Object.keys():
Next TopicShallow Copy and Deep Copy in JavaScript
|