首页 > 解决方案 > 将对象数组转换为对象值的数组

问题描述

我正在使用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 = [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

非常感谢任何帮助!

标签: jqueryarraysjson

解决方案


要执行您需要的操作,您可以使用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);


推荐阅读