When optimizing the project today, I encountered the need to "traverse the properties and values of objects in js". The reason for this requirement is to make a js plug-in that partially refreshes the table content. At first, I went online to create a js paging plug-in, but I was really impatient and couldn’t get it out after a long time! Later I got angry and decided to write one myself. As a result, I encountered this problem!
Problem: Failed to obtain the attribute value of the object by traversing the array of attribute names.
The initial error code is as follows:
for(var i=0;i<dataList.length;i++) { var dataLine="<tr>"; for(var j=0;j<filedList.length;j++){ dataLine+="<td>"+dataList[i].filedList[j]+"</td>"; } dataLine+="</tr>"; $("#"+tableName).append(dataLine); }
First of all, dataList contains an array of objects; filedList contains objects. Array of attribute field names. At first, I thought like this, traverse the dataList, and get an object every time, then nest a for loop, traverse the filedList, get one of its attribute values each time, and then piece it together into a table.
For example: dataList[0] is an Emp object, and Emp has attributes such as id and name. Normally we can get the id value of the current Emp object through dataList[0].id. But if you traverse the attribute field array, you cannot use dataList[0].filedList[0] in this way. This does not mean that the value is not obtained in filedList[0], because I have already obtained the id value of 1 through alert(filedList[0]). So why does the acquisition fail? Because it is looking for a property called filedList[0] in the Emp object! Of course, there is no such attribute in the Emp object, so the acquisition fails as it should. So how do we obtain the attribute value of the object?
------------------------------------------------
Solution Solution: Use "enhanced for loop" to traverse
The correct code is as follows:
for(var i=0;i<dataList.length;i++) { var dataLine="<tr>"; for(var filedName in dataList[i]){ dataLine+="<td>"+dataList[i][filedName]+"</td>"; } dataLine+="</tr>"; $("#"+tableName).append(dataLine); }
Solution: Since dataList[i] is an object, then I can get the attribute name of this object every time, and then Get the attribute value of this attribute through dataList[i][filedName], that is, object [attribute name].
Reference: JS obtains all properties and methods of an object
function displayProp(obj){ var names=""; for(var name in obj){ names+=name+": "+obj[name]+", "; } alert(names); }
From this point of view, the function of js is still very powerful!