Object method commonly used in ES6: object keys(),Object.values() ...

1. Object.assign()

Object.assign() is used to copy the values of all enumerable attributes from one or more source objects to the target object.

Syntax: object assign(obj, ...sources)

  • obj: target object
  • sources: source object, which can be multiple
  • Return target object

Copy an object

const obj = { a: 1 }
const copy = Object.assign({}, obj)
console.log(copy); // { a: 1 }

Merge objects

const obj1 = { a: 1, b: 2 }
const obj2 = { b: 3, c: 4 }
const obj3 = { c: 5, d: 6 }
​
const obj = Object.assign(obj1, obj2, obj3)
console.log(obj) // {a: 1, b: 3, c: 5, d: 6}

Note: if the target object and the source object have attributes with the same name, the following attributes will overwrite the previous attributes; If multiple source objects have properties with the same name, the subsequent source object will overwrite the previous one.

Deep copy of object

Through object Assign() we can copy the object quickly, but this is only a shallow copy because object The assign () method copies enumerable attribute values. If the attribute value of the source object is a reference to an object, the method will only copy its reference.

// Shallow copy
let o1 = {
    a: 0,
    b: { c: 0 }
}
const o2 = Object.assign({}, o1)
o1.b.c = 1 
console.log(o2.c) // 1

So, how do we implement a deep copy of an object?
If you don't consider retaining built-in types, the quickest way is through json Stringify () converts the object to a json string representation, and then parses it back to the object.

// Deep copy: Method 1
let obj1 = { a: 0 , b: { c: 0}}
let obj2 = JSON.parse(JSON.stringify(obj1))
obj1.a = 4 
obj1.b.c = 4 

console.log(obj1)   // { a: 4, b: { c: 4}} 
console.log(obj2)   // { a: 0, b: { c: 0}}

Deep copy can also be realized by recursive method

// Deep copy: Method 2
const obj = {
    name: 'andy',
    age: 18,
    info: {
        gender: 'male',
        schoole: 'NEWS' 
    },
    color: ['pink', 'yellow']
} 
function deepCopy(obj){
    let o = {} 
    for(let k in obj) {  // For here The in method can use object keys(obj). map(k =>{....})  replace
        // 1. Get attribute value
        var item = obj[k]; // 2. Judge which data type the attribute value belongs to
        if(item instanceof Array) { // Is it an array
            o[k] = []
            deepCopy(o[k], item)
        } else if(item instanceof Object) { // Is it an object
            o[k] = {}
            deepCopy(o[k], item)
        } else { // Simple data type
            o[k] = item
        }
    } return o
}
const newObj = deepCopy(obj)
console.log(newObj)

In addition, you can also structured clone algorithm , if you are interested, please check it by yourself.

2. Object.create() creates a new object

Syntax: object create(proto)

  • proto: prototype object of newly created object
  • Returns a new object

use:

const person = {
    isHuman: false,
    printIntroduction: function() {
        console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
    }
}

// Object. Create object in create() mode
const me = Object.create(person)
console.log(me)   // {}
me.name = 'Matthew'   // "name" is a property set on "me", but not on "person"
me.isHuman = true   // inherited properties can be overwritten
me.printIntroduction()   // My name is Matthew. Am I human? true
console.log(me.__proto__ === person)   //true

​// Create objects through new Object()
const me = new Object(person)
console.log(me)   // {isHuman: false, printIntroduction: ƒ}
me.name = 'Matthew' 
me.isHuman = true 
console.log(me)   // {isHuman: true, name: "Matthew", printIntroduction: ƒ}

Object.create() can realize the inheritance of objects through the inheritance of object instances__ proto__ Property to access properties on the prototype chain.

For the object created by the new Object() method, adding properties and methods to the object prototype requires a constructor or class.

function Person(name, age){ 
    this.name=name this.age=age
}
Person.prototype.sayHi = function(){
    console.log(this.name)
}

let p = new Person('jack', 20)
console.log(p.sayHi()) // jack
console.log(p.__proto__ === Person.prototype) // true

3. Object.defineProperty()

Object.defineProperty() adds or modifies an existing property and returns the object.

Syntax: object defineProperty(obj, prop, description)

  • obj: required. Target object

  • prop: required. The name of the attribute to be defined or modified

  • descriptor: required. The characteristics of the target attribute are written in the form of object.

    1. Value: sets the value of the attribute, which is undefined by default
    2. writable: whether the value can be rewritten. true | false. The default is false
    3. enumerable: whether the target attribute can be enumerated. true | false. The default is false
    4. configurable: whether the target attribute can be deleted or the feature can be modified again. true | false. The default is false
const obj = {
    id: 1,
    name: 'phone',
    price: '$599' 
}
Object.defineProperty(obj, 'num', {
    value: 100,
    enumerable: false 
})

console.log(obj)   // {id: 1, name: "phone", price: "$599", num: 100}
console.log(Object.keys(obj))   // ["id", "name", "price"]

4. Object.entires()

Object.entires() traverses and returns an array of key value pairs of enumerable properties of the object

Syntax: object entires(obj)

  • Returns an array of key value pairs for enumerable properties of an object
const obj = {
    a: 'apple',
    b: 'bar' 
}
console.log(Object.entries(obj)) // [ ['a', 'apple'], ['b', 'bar'] ]

for (const [key, value] of Object.entries(obj)) {
    console.log(`${key}: ${value}`) //"a: somestring"  "b: 42"
}

Object.entries(obj).forEach(([key, value]) => {
    console.log(`${key}: ${value}`) // "a: somestring", "b: 42"
})

5. Object.keys() 

Object.keys() is used to get all enumerable properties of the object itself

Syntax: object keys(obj)

  • The effect is similar to for in
  • Returns an array of property names
const obj = {
    id: 1,
    name: 'phone',
    price: '$599',
    num: 100 
}

const objKeys = Object.keys(obj);
console.log(objKeys)   //['id', 'name', 'price', 'num']
​
const arr = ['a', 'b', 'c']
const arrKeys = Object.keys(arr)
console.log(arrKeys)   //['0', '1', '2']

Add: if you only need to obtain the enumerable properties of an object, you can use object Keys or for In loop (for...in loop will get the object's own and inherited enumerable properties, which can be filtered out by using the {hasOwnProperty() method)

6. Object.values()

Object.values() gets all enumerable property values of the object itself

Syntax: object values(obj)

  • Returns an array of property values
const obj = {
    id: 1,
    name: 'phone',
    price: '$599',
    num: 100 
}

const objValues = Object.values(obj);
console.log(objValues); //[1, 'phone', '$599', '100']

Attachment: all properties and methods of the object

Tags: Javascript Front-end ECMAScript

Posted by benji2010 on Mon, 09 May 2022 13:38:14 +0300