【问题标题】:Convert array of objects to an array of the object's values将对象数组转换为对象值的数组
【发布时间】:2021-01-19 13:58:50
【问题描述】:

我正在使用getJSON 获取一组数据,如下所示:

var url = 'http://localhost:5000/api/items';
$.getJSON(url, function(response) {
  var response2 = []
  console.log(response)
});

我的控制台输出如下:

[{"id": 1, "price": 20, "name": "test"}, {"id": 4, "price": 30, "name": "test2"}]

我需要将这些值转换成这种格式的数组:

[[1, 20, "test"], [4, 30, "test2"]]

我尝试了以下代码,但结果不同:

$.each(response, function (key, val) {
  response2.push(val)
});

console.log(response2)  // output = [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

非常感谢任何帮助!

【问题讨论】:

    标签: jquery arrays json


    【解决方案1】:

    要执行您需要的操作,您可以使用Object.values 以数组形式从对象中获取所有属性的值。从那里你可以使用map() 来构建一个包含它们的新数组:

    // AJAX response:
    let response = [{"id": 1, "price": 20, "name": "test"}, {"id": 4, "price": 30, "name": "test2"}];
    
    let  response2 = response.map(Object.values);
    console.log(response2);

    【讨论】:

      【解决方案2】:

      如果您需要使用array 来执行此操作,这是另一种方式。

      演示代码

      var response = [{
        "id": 1,
        "price": 20,
        "name": "test"
      }, {
        "id": 4,
        "price": 30,
        "name": "test2"
      }]
      var outerarray = [];
      $.each(response, function(key, val) {
        innerarray = []
        innerarray.push(val.id, val.price, val.name) //push value
        outerarray.push(innerarray)
      });
      console.log(outerarray)
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

      【讨论】:

      • 非常感谢,对于“菜鸟”的问题,我们深表歉意 :)
      猜你喜欢
      • 2019-07-29
      • 2019-04-26
      • 1970-01-01
      • 2021-05-03
      • 2018-12-04
      • 2021-06-16
      • 1970-01-01
      相关资源
      最近更新 更多