jquery - 将对象数组转换为对象值的数组
问题描述
我正在使用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 = [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
非常感谢任何帮助!
解决方案
要执行您需要的操作,您可以使用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);
推荐阅读
- node.js - Mongoose - 为什么演员表日期失败?
- flutter - StateNotifierProvider 不在 Flutter 中保持状态(Riverpod)
- android - 使用 Hilt 进行依赖注入时如何将运行时参数传递给 ViewModel 的构造函数?
- performance - MDB + ActiveMQ + Weblogic 高负载
- mysql - SQL 查询性能(复杂性分析?)
- ruby-on-rails - 如何去除纱包
- angular - 如何为 API api.rawg.io 构建分页
- python - 最难的python生成器面试题——数字范围的python生成器对象
- django - Django 框架列出所有产品并汇总每个产品的所有销售额
- javascript - 圆环图,在饼图内和向下也有文本