将数组中的多个对象转换为数组

时间:2018-01-19 10:48:49

标签: javascript arrays arr

我想转换一下:

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

进入这个:

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

我尝试过.map()函数,但它不起作用。任何帮助将不胜感激,谢谢!

3 个答案:

答案 0 :(得分:0)

这是一个非常简单的问题,我建议您在发布问题之前先引用javascript核心功能。

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

答案 1 :(得分:0)

如果要确保跨不同JS引擎的数组中值的顺序,可以创建一个属性键数组(order),并迭代它以获取所请求顺序的值。 / p>

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

答案 2 :(得分:0)

不考虑订单,只需使用before do allow(Bugsnag).to receive(:notify) get :index end subject { response } it { should_not be_successful } it "notifies Bugsnag" do expect(Bugsnatch).to have_received(:notify) end

即可
map

但您需要先指定订单

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

然后使用var order = ["order_id", "product_id", "product_after_price"];

map

<强>演示

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