【问题标题】:Convert multiple objects in array into an array将数组中的多个对象转换为数组
【发布时间】:2018-01-19 10:48:49
【问题描述】:

我想转换这个:

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() 函数,但它不起作用。任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 无法保证对象中键的顺序,不确定您是否会得到一个直截了当的答案。
  • 试试arr.map( s => Object.values(s) )
  • @gurvinder372 这行得通,谢谢。我不明白为什么人们会用“-1”直接攻击我,我是初学者,我是来学习的。嘘。
  • 你检查过分享的答案吗?

标签: javascript arrays arr


【解决方案1】:

如果您想确保数组中的值在不同 JS 引擎中的顺序,您可以创建一个属性键数组 (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);

【讨论】:

    【解决方案2】:

    不考虑顺序,直接用map

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

    但需要先指定顺序

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

    然后使用map

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

    演示

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

    【讨论】:

      【解决方案3】:

      这确实是一个非常简单的问题,我的建议是,您应该先参考 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);

      【讨论】:

        猜你喜欢
        • 2020-06-17
        • 2020-10-04
        • 2023-02-06
        • 1970-01-01
        • 2018-05-22
        • 2021-04-23
        • 2021-05-03
        • 2018-12-04
        • 2021-06-16
        相关资源
        最近更新 更多