Search code examples
javascriptarraysarr

Convert multiple objects in array into an array


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!


Solution

  • 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);