In JavaScript, almost all objects are instances of object type, and they inherit properties and methods from Object.prototype. The object constructor creates an object wrapper for the given value. Object constructor, which creates an object based on the given parameters.
- If the given value is null or undefined, an empty object is created and returned
- If a value of a basic type is passed in, an object of its wrapper type will be constructed
- If a value of reference type is passed in, it will still be returned, and the variable copied by them will maintain the same reference address as the source object
Object.assign()
The Object.assign() method is used to assign the values of all enumerable attributes from one or more source objects to the target object. It will return the target object.
grammar
Object.assign(target, ...sources)
parameter
-
target
Target object.
-
sources
Source object.
Return value
- Target object.
example
const target = { a: 1, b: 2 }; const source = { b: 4, c: 5 }; const returnedTarget = Object.assign(target, source); console.log(target); // expected output: Object { a: 1, b: 4, c: 5 } console.log(returnedTarget); // expected output: Object { a: 1, b: 4, c: 5 }
Object.create()
The Object.create() method creates a new object and uses the existing object to provide the name of the newly created object__ proto__.
grammar
Object.create(proto,[propertiesObject])
parameter
-
proto
The prototype object of the newly created object.
-
propertiesObject
Optional. You need to pass in an object whose property type refers to the second parameter of Object.defineProperties(). If the parameter is specified and not undefined, the self enumerable property of the incoming object (that is, the property defined by itself, rather than the enumerated property on its prototype chain) will add the specified property value and corresponding property descriptor to the newly created object.
Return value
- A new object with the specified prototype object and properties.
example
const person = { isHuman: false, printIntroduction: function() { console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`); } }; const me = Object.create(person); me.name = 'Matthew'; // "name" is a property set on "me", but not on "person" me.isHuman = true; // inherited properties can be overwritten me.printIntroduction(); // expected output: "My name is Matthew. Am I human? true"
Object.values()
The Object.values() method returns an array of all enumerable attribute values of a given object, and the order and use of the values for...in The order of loops is the same (the difference is that the for in loop enumerates the attributes in the prototype chain).
grammar
Object.values(obj)
parameter
-
obj
An object that returns enumerable property values.
Return value
- An array containing all enumerable property values of the object itself.
describe
Object.values() returns an array whose elements are enumerable attribute values found on the object. The order of attributes is the same as that given by manually looping the attribute values of the object.
example
var obj = { foo: 'bar', baz: 42 }; console.log(Object.values(obj)); // ['bar', 42] // array like object var obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(Object.values(obj)); // ['a', 'b', 'c'] // array like object with random key ordering // when we use numeric keys, the value returned in a numerical order according to the keys var an_obj = { 100: 'a', 2: 'b', 7: 'c' }; console.log(Object.values(an_obj)); // ['b', 'c', 'a'] // getFoo is property which isn't enumerable var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } }); my_obj.foo = 'bar'; console.log(Object.values(my_obj)); // ['bar'] // non-object argument will be coerced to an object console.log(Object.values('foo')); // ['f', 'o', 'o']
Object.entries()
The Object.entries() method returns an array of key value pairs of enumerable attributes of a given object, which is arranged in the same order as when traversing the object using the for...in loop (the difference is that the for in loop also enumerates attributes in the prototype chain).
grammar
Object.entries(obj)
parameter
-
obj
An object that can return key value pairs of its enumerable properties.
Return value
- nothing
example
const obj = { foo: 'bar', baz: 42 }; console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ] // array like object const obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ] // array like object with random key ordering const anObj = { 100: 'a', 2: 'b', 7: 'c' }; console.log(Object.entries(anObj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ] // getFoo is property which isn't enumerable const myObj = Object.create({}, { getFoo: { value() { return this.foo; } } }); myObj.foo = 'bar'; console.log(Object.entries(myObj)); // [ ['foo', 'bar'] ] // non-object argument will be coerced to an object console.log(Object.entries('foo')); // [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ] // iterate through key-value gracefully const obj = { a: 5, b: 7, c: 9 }; for (const [key, value] of Object.entries(obj)) { console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" } // Or, using array extras Object.entries(obj).forEach(([key, value]) => { console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" });
example
const object1 = { a: 'somestring', b: 42 }; for (const [key, value] of Object.entries(object1)) { console.log(`${key}: ${value}`); } // expected output: // "a: somestring" // "b: 42"
Object.freeze()
The Object.freeze() method can freeze an object. A frozen object can no longer be modified; If an object is frozen, you cannot add new attributes to the object, delete existing attributes, modify the enumerability, configurability and Writeability of existing attributes of the object, and modify the value of existing attributes. In addition, after freezing an object, the prototype of the object cannot be modified. Free () returns the same object as the passed in parameter.
grammar
Object.freeze(obj)
parameter
-
obj
The object to be frozen.
Return value
- Frozen objects.
example
Freeze object
var obj = { prop: function() {}, foo: 'bar' }; // New properties will be added, and existing properties may // Will be modified or removed obj.foo = 'baz'; obj.lumpy = 'woof'; delete obj.prop; // Both the object passed as a parameter and the object returned are frozen // Therefore, it is not necessary to save the returned object (because the two objects are equal) var o = Object.freeze(obj); o === obj; // true Object.isFrozen(obj); // === true // Now any change will fail obj.foo = 'quux'; // Do nothing in silence // Silently do not add this property obj.quaxxor = 'the friendly duck'; // In strict mode, this behavior throws TypeErrors function fail(){ 'use strict'; obj.foo = 'sparky'; // throws a TypeError delete obj.quaxxor; // Returns true because the quaxxor property has never been added obj.sparky = 'arf'; // throws a TypeError } fail(); // An attempt was made to change a property through Object.defineProperty // The following two statements will throw TypeError Object.defineProperty(obj, 'ohai', { value: 17 }); Object.defineProperty(obj, 'foo', { value: 'eit' }); // You cannot change the prototype // The following two statements will throw TypeError Object.setPrototypeOf(obj, { x: 20 }) obj.__proto__ = { x: 20 }
Freeze array
let a = [0]; Object.freeze(a); // The array cannot be modified now a[0]=1; // fails silently a.push(2); // fails silently // In strict mode such attempts will throw TypeErrors function fail() { "use strict" a[0] = 1; a.push(2); } fail();
Frozen objects are immutable. But not always. The following example shows that the frozen object is not a constant object (shallow freezing).
obj1 = { internal: {} }; Object.freeze(obj1); obj1.internal.a = 'aValue'; obj1.internal.a // 'aValue'
For a constant object, the entire reference graph (directly and indirectly referring to other objects) can only refer to immutable frozen objects. Frozen objects are considered immutable because the entire object state (values and references to other objects) in the entire object is fixed. Note that strings, numbers, and Booleans are always immutable, while functions and arrays are objects.
To make an object immutable, you need to recursively freeze each property of type object (deep freeze). When you know that the object does not contain any ring (circular reference) in the reference graph, you will use this mode one by one according to your design, otherwise an infinite loop will be triggered. The enhancement to deepFreeze() will be an internal function with a receive path (such as Array) parameter, so that deepFreeze() can be called recursively when the object enters unchanged. You are still at risk of freezing objects that should not be frozen, such as [window].
// Deep freezing function function deepFreeze(obj) { // Retrieve the attribute name defined on obj var propNames = Object.getOwnPropertyNames(obj); // Freeze attributes before freezing itself propNames.forEach(function(name) { var prop = obj[name]; // If prop is an object, freeze it if (typeof prop == 'object' && prop !== null) deepFreeze(prop); }); // No OP if already frozen return Object.freeze(obj); } obj2 = { internal: {} }; deepFreeze(obj2); obj2.internal.a = 'anotherValue'; obj2.internal.a; // undefined
Object.fromEntries()
The Object.fromEntries() method converts the list of key value pairs into an object.
grammar
Object.fromEntries(iterable);
parameter
-
iterable
Similar to Array, Map or other iterative objects that implement iterative protocols.
Return value
- A new object whose corresponding attribute is provided by the iteration object entry.
Example
Convert Map to Object
Map can be converted to Object through Object.fromEntries:
const map = new Map([ ['foo', 'bar'], ['baz', 42] ]); const obj = Object.fromEntries(map); console.log(obj); // { foo: "bar", baz: 42 }
Convert Array to Object
Through Object.fromEntries, you can convert Array to Object:
const arr = [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]; const obj = Object.fromEntries(arr); console.log(obj); // { 0: "a", 1: "b", 2: "c" }
Object conversion
Object.fromEntries () is the opposite method to Object.entries(). The array processing function can be used to convert objects as follows:
const object1 = { a: 1, b: 2, c: 3 }; const object2 = Object.fromEntries( Object.entries(object1) .map(([ key, val ]) => [ key, val * 2 ]) ); console.log(object2); // { a: 2, b: 4, c: 6 }
Object.is()
The Object.is() method determines whether two values are the same value.
grammar
Object.is(value1, value2);
parameter
-
value1
The first value to be compared.
-
value2
The second value to be compared.
Return value
- A Boolean type indicates whether two parameters are the same value.
example
// The Object.is() method determines whether two values are the same value. The two values are equal if the following conditions are met: // All undefined // All null // Both are true or false // Are strings of the same length and the same characters are arranged in the same order // Are the same object (meaning that each object has the same reference) // All numbers and // All + 0 // All - 0 // It's all NaN // Or both are non-zero and non NaN and the same value
Object.keys()
The Object.keys() method will return an array composed of the enumerable attributes of a given object. The order of the attribute names in the array is consistent with the order returned when the object is traversed in a normal loop.
grammar
Object.keys(obj)
parameter
-
obj
The object whose enumeration properties you want to return.
Return value
- An array of strings representing all enumerable properties of a given object.
example
// simple array var arr = ['a', 'b', 'c']; console.log(Object.keys(arr)); // console: ['0', '1', '2'] // array like object var obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(Object.keys(obj)); // console: ['0', '1', '2'] // array like object with random key ordering var anObj = { 100: 'a', 2: 'b', 7: 'c' }; console.log(Object.keys(anObj)); // console: ['2', '7', '100'] // getFoo is a property which isn't enumerable var myObj = Object.create({}, { getFoo: { value: function () { return this.foo; } } }); myObj.foo = 1; console.log(Object.keys(myObj)); // console: ['foo']
If you want to get all the properties of an object, even those that cannot be enumerated, please check Object.getOwnPropertyNames.
Object.values()
The Object.values() method returns an array of all enumerable attribute values of a given object, and the order and use of the values for...in The order of loops is the same (the difference is that the for in loop enumerates the attributes in the prototype chain).
grammar
Object.values(obj)
parameter
-
obj
An object that returns enumerable property values.
Return value
- An array containing all enumerable property values of the object itself.
Example
var obj = { foo: 'bar', baz: 42 }; console.log(Object.values(obj)); // ['bar', 42] // array like object var obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(Object.values(obj)); // ['a', 'b', 'c'] // array like object with random key ordering // when we use numeric keys, the value returned in a numerical order according to the keys var an_obj = { 100: 'a', 2: 'b', 7: 'c' }; console.log(Object.values(an_obj)); // ['b', 'c', 'a'] // getFoo is property which isn't enumerable var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } }); my_obj.foo = 'bar'; console.log(Object.values(my_obj)); // ['bar'] // non-object argument will be coerced to an object console.log(Object.values('foo')); // ['f', 'o', 'o']
Object.seal()
The Object.seal() method closes an object, prevents the addition of new properties, and marks all existing properties as non configurable. The value of the current property can be changed as long as it is writable.
grammar
Object.seal(obj)
parameter
-
obj
The object to be sealed.
Return value
- Sealed objects.
example
var obj = { prop: function() {}, foo: 'bar' }; // You can add new properties // You can change or delete existing properties obj.foo = 'baz'; obj.lumpy = 'woof'; delete obj.prop; var o = Object.seal(obj); o === obj; // true Object.isSealed(obj); // === true // You can still modify the attribute values of sealed objects obj.foo = 'quux'; // However, you cannot redefine a property as an accessor property // vice versa Object.defineProperty(obj, 'foo', { get: function() { return 'g'; } }); // throws a TypeError // Any change other than the attribute value will fail obj.quaxxor = 'the friendly duck'; // Adding properties will fail delete obj.foo; // Deleting properties will fail // In strict mode, such an attempt will throw an error function fail() { 'use strict'; delete obj.foo; // throws a TypeError obj.sparky = 'arf'; // throws a TypeError } fail(); // Adding a property through Object.defineProperty will result in an error Object.defineProperty(obj, 'ohai', { value: 17 }); // throws a TypeError Object.defineProperty(obj, 'foo', { value: 'eit' }); // Modify the property value through Object.defineProperty
Object.defineProperties()
The Object.defineProperties() method directly defines a new property or modifies an existing property on an object and returns the object.
grammar
Object.defineProperties(obj, props)
parameter
-
obj
An object on which properties are defined or modified.
-
props
The object whose enumerable properties or modified property descriptors you want to define. There are two kinds of property descriptors in the object: data descriptor and accessor descriptor (for more details, see Object.defineProperty()). The descriptor has the following keys:
configurable``true only the type of the attribute descriptor can be changed and the attribute can be deleted from the corresponding object. The default value is false``enumerable``true. The attribute appears only when enumerating the attributes on the corresponding object. The default is false``value the value associated with the attribute. Can be any valid JavaScript value (number, object, function, etc.). The default value is undefined.writable``true. Only when the value associated with this attribute is changed by the assignment operator (EN US). The default value is false``get as the getter function of the property. If there is no getter, it is undefined. The return value of the function will be used as the value of the property. The default is undefined``set as the setter function of the property. If there is no setter, it is undefined. The function will only accept the new value assigned to the property by the parameter. The default is undefined
Return value
- The object passed to the function.
example
var obj = {}; Object.defineProperties(obj, { 'property1': { value: true, writable: true }, 'property2': { value: 'Hello', writable: false } // etc. etc. });
Object.defineProperty()
The Object.defineProperty() method will directly define a new property on an object, or modify the existing property of an object and return the object.
grammar
Object.defineProperty(obj, prop, descriptor)
parameter
-
obj
The object whose properties are to be defined.
-
prop
The name or Symbol of the attribute to define or modify.
-
descriptor
The property descriptor to define or modify.
Return value
- The object passed to the function.
example
const object1 = {}; Object.defineProperty(object1, 'property1', { value: 42, writable: false }); object1.property1 = 77; // throws an error in strict mode console.log(object1.property1); // expected output: 42
Object.getOwnPropertyDescriptor()
The Object.getOwnPropertyDescriptor() method returns the property descriptor corresponding to the last self owned property of the specified object. (self owned attribute refers to the attribute directly assigned to the object, which does not need to be searched from the prototype chain)
grammar
Object.getOwnPropertyDescriptor(obj, prop)
parameter
-
obj
Target object to find
-
prop
Attribute name within target object
Return value
- If the specified property exists on the object, its property descriptor object is returned; otherwise, undefined is returned.
example
var o, d; o = { get foo() { return 17; } }; d = Object.getOwnPropertyDescriptor(o, "foo"); // d { // configurable: true, // enumerable: true, // get: /*the getter function*/, // set: undefined // } o = { bar: 42 }; d = Object.getOwnPropertyDescriptor(o, "bar"); // d { // configurable: true, // enumerable: true, // value: 42, // writable: true // } o = {}; Object.defineProperty(o, "baz", { value: 8675309, writable: false, enumerable: false }); d = Object.getOwnPropertyDescriptor(o, "baz"); // d { // value: 8675309, // writable: false, // enumerable: false, // configurable: false // }
Object.getOwnPropertyDescriptors()
The Object.getOwnPropertyDescriptors() method is used to obtain descriptors of all self attributes of an object.
grammar
Object.getOwnPropertyDescriptors(obj)
parameter
-
obj
Any object
Return value
- Descriptors of all self attributes of the specified object. If there are no self attributes, an empty object is returned.
example
Shallow copy an object
The Object.assign() method can only copy the enumerable properties of the source object. At the same time, the properties of the properties cannot be copied during copying. In addition, the accessor properties will be converted into data properties, and the prototype of the source object cannot be copied. This method can be combined with the Object.create() method to achieve the above.
Object.create( Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj) );
Create subclass
A typical way to create a subclass is to define a subclass, prototype it as an instance of a superclass, and then define properties on that instance. This is not elegant, especially for getters and setter s. Instead, you can use this code to set up the prototype:
function superclass() {} superclass.prototype = { // Methods and properties are defined here }; function subclass() {} subclass.prototype = Object.create(superclass.prototype, Object.getOwnPropertyDescriptors({ // Methods and properties are defined here }));
Object.getOwnPropertyNames()
The Object.getOwnPropertyNames() method returns an array of property names of all its own properties of the specified object (including non enumerable properties but excluding those with Symbol values as names).
grammar
Object.getOwnPropertyNames(obj)
parameter
-
obj
The names of enumerable and non enumerable properties of an object are returned.
Return value
- An array of strings corresponding to its own properties found on the given object.
example
Use Object.getOwnPropertyNames()
var arr = ["a", "b", "c"]; console.log(Object.getOwnPropertyNames(arr).sort()); // ["0", "1", "2", "length"] // Class array object var obj = { 0: "a", 1: "b", 2: "c"}; console.log(Object.getOwnPropertyNames(obj).sort()); // ["0", "1", "2"] // Use Array.forEach to output the attribute name and attribute value Object.getOwnPropertyNames(obj).forEach(function(val, idx, array) { console.log(val + " -> " + obj[val]); }); // output // 0 -> a // 1 -> b // 2 -> c //Cannot enumerate properties var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; }, enumerable: false } }); my_obj.foo = 1; console.log(Object.getOwnPropertyNames(my_obj).sort()); // ["foo", "getFoo"]
If you only need to get enumerable properties, check Object.keys or use the for...in loop (you can also get enumerable properties on the prototype chain, but you can filter them out with the hasOwnProperty() method).
The following example demonstrates that this method will not obtain the attributes on the prototype chain:
function ParentClass() {} ParentClass.prototype.inheritedMethod = function() {}; function ChildClass() { this.prop = 5; this.method = function() {}; } ChildClass.prototype = new ParentClass; ChildClass.prototype.prototypeMethod = function() {}; console.log( Object.getOwnPropertyNames( new ChildClass() // ["prop", "method"] ) );
Get only non enumerable properties
The following example uses the Array.prototype.filter() method to remove enumerable properties (obtained by the Object.keys() method) from all property name arrays (obtained by the Object.getOwnPropertyNames() method), and the remaining properties are non enumerable properties:
var target = myObject; var enum_and_nonenum = Object.getOwnPropertyNames(target); var enum_only = Object.keys(target); var nonenum_only = enum_and_nonenum.filter(function(key) { var indexInEnum = enum_only.indexOf(key); if (indexInEnum == -1) { // Not found in enum_only key concentration means that this key is not enumerable, // So return true to keep it in the filtered results return true; } else { return false; } }); console.log(nonenum_only);
Note: Array.filter(filt_func)Method to create a new array, It contains all the elements of the test implemented by the provided function.
Object.getOwnPropertySymbols()
The Object.getOwnPropertySymbols() method returns an array of all Symbol properties of a given object itself.
grammar
Object.getOwnPropertySymbols(obj)
parameter
-
obj
The object to return the Symbol property.
Return value
- An array of all Symbol properties found on the given object itself.
example
var obj = {}; var a = Symbol("a"); var b = Symbol.for("b"); obj[a] = "localSymbol"; obj[b] = "globalSymbol"; var objectSymbols = Object.getOwnPropertySymbols(obj); console.log(objectSymbols.length); // 2 console.log(objectSymbols) // [Symbol(a), Symbol(b)] console.log(objectSymbols[0]) // Symbol(a)
Object.getPrototypeOf()
The Object.getPrototypeOf() method returns the Prototype of the specified object (the value of the internal [[Prototype]] attribute).
grammar
Object.getPrototypeOf(object)
parameter
-
obj
The object whose prototype you want to return.
Return value
- Prototype of the given object. null if there is no inherited property.
example
const prototype1 = {}; const object1 = Object.create(prototype1); console.log(Object.getPrototypeOf(object1) === prototype1); // expected output: true
Reference address: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object