-1

I want to convert this:

var x = [{ order_id: 10,
           product_id: 5,
           product_after_price: 50 },
         { order_id: 10,
           product_id: 6,
           product_after_price: 50 }]

Into this:

[[10, 5, 50], [10, 6, 50]]

I tried .map() function but it just doesn't work. Any help would be appreciated, thank you!

Cedric Hadjian
  • 849
  • 12
  • 25

3 Answers3

1

If you want to ensure the order of the values in the array across different JS engines, you can create an array of property keys (order), and iterate it to get the values in the requested order.

const order = ['order_id', 'product_id', 'product_after_price'];

const x = [{"order_id":10,"product_id":5,"product_after_price":50},{"order_id":10,"product_id":6,"product_after_price":50}];
           
const result = x.map((o) => order.map((key) => o[key]));

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

It is really the very simple question, it is my kind advice that you should refer javascript core functions first before post a question here.

var x = [{ order_id: 10,
           product_id: 5,
           product_after_price: 50 },
         { order_id: 10,
           product_id: 6,
           product_after_price: 50 }]
        
var arrValues = []
for(var index=0; index< x.length; index++){
 if(!!x[index]){
   arrValues.push(Object.values(x[index]));
  }
}
console.log(arrValues);
Dipak
  • 2,248
  • 4
  • 22
  • 55
0

Without considering order, simply use map

arr.map( s => Object.values(s) )

But you need to specify the order first

var order = ["order_id", "product_id", "product_after_price"];

then use map

var output = arr.map( function(item){
   return order.reduce( function(a,c){
      a.push( item[c] );
     return a;
   }, []);
})

Demo

var order = ["order_id", "product_id", "product_after_price"];
var x = [{
    order_id: 10,
    product_id: 5,
    product_after_price: 50
  },
  {
    order_id: 10,
    product_id: 6,
    product_after_price: 50
  }
];
var output = x.map(function(item) {
  return order.reduce(function(a, c) {
    a.push( item[c] );
    return a;
  }, []);
});

console.log(output);
gurvinder372
  • 66,980
  • 10
  • 72
  • 94