In JavaScript, the Object.keys()
and Object.values()
methods are related object functions that allow you to extract information from objects. Here's an explanation of each function:
Object.keys(): The
Object.keys()
method returns an array containing the enumerable property names (keys) of an object. It takes the object as an argument and returns an array of strings representing the object's keys.
var obj = { a: 1, b: 2, c: 3 };
var keys = Object.keys(obj);
console.log(keys); // Output: ["a", "b", "c"]
In this example,
Object.keys(obj)
returns an array["a", "b", "c"]
, which represents the keys of theobj
object.Object.values(): The
Object.values()
method returns an array containing the enumerable property values of an object. It takes the object as an argument and returns an array of values.
var obj = { a: 1, b: 2, c: 3 };
var values = Object.values(obj);
console.log(values); // Output: [1, 2, 3]
In this example,
Object.values(obj)
returns an array[1, 2, 3]
, which represents the values of theobj
object.
Both Object.keys()
and Object.values()
only consider enumerable properties of an object, excluding properties in the prototype chain with the exception of properties in plain objects created with Object.create(null)
.
These functions are useful for iterating over object properties, performing transformations, filtering, or any operation that requires accessing the keys or values of an object. They provide a convenient way to work with object data in a more array-like manner.
object.assign
object.entries
No comments:
Post a Comment