Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an array of objects to array of the objects' values

I am trying to convert this array

let orders = [   {  amount: '100', user: 'admin', date: 'March 6, 2019' },   {  amount: '120', user: 'admin', date: 'March 6, 2019' },   {  amount: '80', user: 'admin', date: 'March 7, 2019' },   {  amount: '200', user: 'admin', date: 'March 7, 2019' }, ]; 

to something like this

orders = [   ['100', 'admin', 'March 6, 2019'],   ['120', 'admin', 'March 6, 2019'],   ['80', 'admin', 'March 7, 2019'],   ['200', 'admin', 'March 7, 2019'], ]; 

and I have read that Objects.values() returns the values in an array, so I tried to iterate through the order array by using forEach() and using the Object.values on each item in the array.

let newOrders = orders.forEach(order => {   return Object.values(order); }); 

I don't know if what I am doing is right and I am new to Javascript. Please help me.

like image 729
sunny_adriann Avatar asked Mar 07 '19 10:03

sunny_adriann


People also ask

How do you convert an array of objects to an array?

To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .

How do you convert an array of objects into an object object?

The quickest way to convert an array of objects to a single object with all key-value pairs is by using the Object. assign() method along with spread operator syntax ( ... ). The Object.

How do you convert the values of an object into an array?

You can convert its values to an array by doing: var array = Object. keys(obj) . map(function(key) { return obj[key]; }); console.

How do you transform an array of objects?

To convert an array of objects to a Map , call the map() method on the array and on each iteration return an array containing the key and value. Then pass the array of key-value pairs to the Map() constructor to create the Map object.


1 Answers

As order of values in array returned by Object.values() isn't guaranteed, you should consider use of .map() with some Object Destructuring. You can then extract object properties in separate variables and return them in desired order explicitly.

const data = [    { amount: '100', user: 'admin', date: 'March 6, 2019' },    { amount: '120', user: 'admin', date: 'March 6, 2019' },    { amount: '80',  user: 'admin', date: 'March 7, 2019' },    { amount: '200', user: 'admin', date: 'March 7, 2019' }  ];    const result = data.map(({ amount, user, date }) => [amount, user, date]);    console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 143
Mohammad Usman Avatar answered Sep 22 '22 01:09

Mohammad Usman