A friend asked how to convert an object into an array. When I asked him why he wanted to convert it, he told me that arrays can be traversed using js loops, but objects cannot. In fact, objects can also be traversed in a loop. You can loop without conversion! It means you are not very proficient in some operations of js or jquery! Here I will briefly introduce it!
Case
Let’s look at the following objects:
var data={ 张三:69, 李四:72, 王五:90, 二麻子:88, 前端博客:100, haorooms : 98, 王大壮:99 }
Suppose the above is a key and a value object returned by the background (I believe you often encounter this kind of object!), now you need to bind this content to a table in a loop. Some friends don’t know how to operate the object loop! Today I will introduce two methods to you!
Method 1:
Use $.each to loop!
If you don’t know $.each, I suggest you search it online. Of course, you can also search for "the difference between jquery's $().each and $.each". I won't go into details about their differences here. Some friends may use $().each more. Today I will mainly introduce $.each to you.
$.each() can traverse arrays and objects. Here’s how:
$.each([{“name”:”haorooms”,”email”:”bb@126.com”},{“name”:”qianduan”,”email”:”aa@hao.com”}],function(i,n) { alert(“索引:”+i,”对应值为:”+n.name); });
You can also traverse like this:
var arr1 = [ “one”, “two”, “three”, “four”, “five” ]; $.each(arr1, function(){ alert(this); });
Output: one two three four five
The best thing is that you can traverse the array:
var obj =data;//上面复制的data $.each(obj, function(key, val) { alert(obj[key]);//可以输出成绩 console.log(key);//可以输出姓名 });
Method 2:
Use for in loop to traverse obj
For the above object, we can write like this to loop!
for(var i in data){ console.dir(i);//输出姓名 console.dir(data[i]);//输出分数 }
I believe everyone should be familiar with the for in loop! The most commonly used for loop is for(var i=0;i In addition, if we encounter the following objects: We can use data.haorooms to get 98, but if we use "data.Front-end Blog", an error will be reported. Therefore, when we use Chinese characters as the key value, we should use data["Front-end Blog"] when selecting, this way to select, don't use dots anymore. The above is the method of looping through object objects in jquery. I hope it will be helpful to everyone's learning.
var data={
张三:69,
李四:72,
王五:90,
二麻子:88,
前端博客:100,
haorooms : 98,
王大壮:99
}