Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

question from:https://stackoverflow.com/questions/55041867/convert-an-array-of-objects-to-array-of-the-objects-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
83 views
Welcome To Ask or Share your Answers For Others

1 Answer

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; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...