Vuejs object operations: convert objects to arrays, take the property key and value values of objects, and merge multiple objects into one object

1. Take the key of the object

Object.keys(obj) returns a string array representing all enumerable properties of a given object

var obj = {
    
     foo: 'bar', baz: 42 };
console.log(Object.keys(obj)); // ['foo', 'baz']

2. Take the value of the object

Method 1: **Object.values(obj)** returns an array of all enumerable property values ​​of a given object itself, the order of the values ​​is the same as the order of using the for...in loop (the difference lies in the for-in loop enumeration Properties in the prototype chain).

var obj = {
    
     foo: 'bar', baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]
console.log(Object.values('foo')); // ['f', 'o', 'o']

Method Two:

let obj = {
    
    
        a:'aa',
        b:'bb',
        c:'cc',
        d:'dd'
    };
for(let i in obj){
    
    
 console.log(i); //a b c d
 console.log(obj[i]); // aa bb cc dd
}
//如果想把值整合在一起,可以var一个数组,然后将值push进数组里

Method three:

var obj = {
    
     foo: 'bar', baz: 42 };
Object.keys(obj).map((key)=>{
    
        console.log(obj[key])});//依次返回 bar 42

3. Take out both the key and value and convert them into an array

Object.entries() returns an array, the member is the key-value pair array of all enumerable properties of the parameter object itself (without inheritance)

var obj = {
    
     foo: 'bar', baz: 42 };
console.log(Object.entries(obj)); // [['foo', 'baz'],['bar',42]]

4. Combine multiple objects into one and remove duplicates

The Object.assign method is used to copy the values ​​of all enumerable properties from one or more source objects to the target object. It will return the target object.

const target = {
    
     a: 1, b: 2 };
const source = {
    
     b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);//{a: 1, b: 4, c: 5}

Guess you like

Origin blog.csdn.net/GongWei_/article/details/109670992