Open In App

How to Convert an Array of Objects into an Array of Arrays ?

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

An Array of objects is an array that contains multiple objects as its elements which can be converted into an array of arrays i.e. an array that contains multiple arrays as its elements. There are several methods listed below to achieve this task.

Using Object.keys() and Object.values() methods

The Object.keys() method is used to create an array of object keys while the Object.values() method is used to create an array of values contained by the object.

Example: The below example uses the Object.keys() & Object.values() methods to convert an array of objects into an array of arrays.

Javascript




let arrOfObj = [
    { "Name": "Robert", "Gender": 'M', "Age": 20 },
    { "Name": "Aliana", "Gender": 'F', "Age": 34 },
]
 
const convertToArrofArr = (arrOfObj) => {
    const valuesArray = [];
    const keysArray = [];
    for (let i = 0; i < arrOfObj.length; i++) {
        let currKey = Object.keys(arrOfObj[i]);
        let currValue = Object.values(arrOfObj[i]);
        keysArray.push(currKey);
        valuesArray.push(currValue);
    }
    console.log("Keys Array: ", keysArray);
    console.log("Values Array: ", valuesArray);
}
 
convertToArrofArr(arrOfObj);


Output

Keys Array:  [ [ 'Name', 'Gender', 'Age' ], [ 'Name', 'Gender', 'Age' ] ]
Values Array:  [ [ 'Robert', 'M', 20 ], [ 'Aliana', 'F', 34 ] ]

Using Javascript map() method

The map() method allows us to access every key in the array’s objects and store them in new array. Similar approach has been followed to access the values of the array of objects which are also stored in the new array.

Example : The below code will explain the use of map() method to convert array of objects into array of arrays.

Javascript




let arrOfObj = [
    { "Name": "Robert", "Gender": 'M', "Age": 20 },
    { "Name": "Aliana", "Gender": 'F', "Age": 34 },
]
 
const convertToArrofArr = (arrOfObj) => {
    const keysArray = [];
    const valuesArray = [];
    arrOfObj.map(obj => {
        for (let key in obj) {
            keysArray.push(key);
        }
    });
 
    arrOfObj.map(obj => {
        for (let key in obj) {
            valuesArray.push(obj[key]);
        }
    });
    console.log("Keys Array: ", keysArray);
    console.log("Values Array: ", valuesArray);
}
 
convertToArrofArr(arrOfObj);


Output

Keys Array:  [ 'Name', 'Gender', 'Age', 'Name', 'Gender', 'Age' ]
Values Array:  [ 'Robert', 'M', 20, 'Aliana', 'F', 34 ]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads