gpt4 book ai didi

javascript - 如何使用jquery将对象转换为数组

转载 作者:行者123 更新时间:2023-11-30 09:47:05 24 4
gpt4 key购买 nike

我有以下使用 jquery $.get 从 json 文件创建的对象。控制台日志(数组);

 [Object, Object, Object, Object, Object, Object, Object, Object]
0
:
Object
country
:
"Cameroon"
employ_count
:
50
__proto__
:
Object
1
:
bject
7
:
Object
length:8
__proto__
:
Array[0]

我正在尝试将每个对象转换为这种类型的数组 ['Cameroon', 58], ['Germany', 58]...

我尝试使用 jquery $.makeArray

var array = $.makeArray(emObj);

但这仍然返回一个对象。

最佳答案

如果我没理解错的话,你的输入是一个对象数组,而你想要的输出是一个数组数组。使用 jQuery 的 $.map() method 很容易做到这一点,但是为此使用 jQuery 的唯一原因是如果您支持 IE < 9,因为所有现代浏览器都支持 native Array.prototype.map()方法:

var input = {
"countries": [
{ "country": "Australia", "employ_count": 22 },
{ "country": "Cameroon", "employ_count": 50 },
{ "country": "Germany", "employ_count": 13 }
]
};

var output = input.countries.map(function(v) {
return [v.country, v.employ_count];
});

var outputWithjQuery = $.map(input.countries, function(v) {
return [[v.country, v.employ_count]];
});

console.log(output);
console.log(outputWithjQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

请注意,jQuery 版本中的双 [[ ... ]] 不是拼写错误:如果您从 $.map() 函数返回一个数组jQuery 会将其展平,并返回一个元素的数组,该元素是您想要修复的实际数组。 ( native .map() 方法没有此“功能”。)

关于javascript - 如何使用jquery将对象转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38448834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com