Skip to main content

[Thủ Thuật JavaScript] Hướng dẫn Convert một Object thành Array bằng JavaScript

Giới thiệu các method để convert Object to Array trong JavaScript

Convert Object to Array trong JavaScript sử dụng 3 method Object.keys(), Object.values() và Object.entries().

Xem các ví dụ dưới đây

Method 1: Object.keys()


const animal = {  
    first: 'The',  
    last: 'Lion'  
};  

const propertyNames=Object.keys(animal);  

console.log(propertyNames);  
// The Lion

Method 2: Object.values()

const animal = {  
    first: 'The',  
    last: 'Lion'  
};  

const propertyValues=Object.values(animal);  

console.log(propertyValues);
//['The', 'Lion']  

 

Method 3: Object.entries()

const animal = {  
    first: 'The',  
    last: 'Lion'  
};  

const entries=Object.entries(animal);  

console.log(entries);  

//[['first', 'The '] , ['last', 'Lion'] ]

Hướng dẫn Convert một Object thành Array bằng JavaScript

Cho một Object như sau:

var obj = {
    a: "hello",
    b: "this is",
    c: "javascript!",
};

Convert Object thành array bằng JavaScript

var array = Object.keys(obj)
    .map(function(key) {
        return obj[key];
    });

console.log(array); // ["hello", "this is", "javascript!"]