jquery dynamically traverses the properties and values of Json objects

  • 2021-07-04 18:40:19
  • OfStack

1. Traverse the properties of the json object


// Definition json Object 
 var person= {
 name: 'zhangsan',
 pass: '123',

 fn: function(){

   alert(this.name+" Password of ="+this.pass);

 }
 }
 // Traversal person Property includes methods. If you don't want to display methods, you can use typeof(person[item])== "function" To judge 
 for(var item in person){
 alert("person Medium "+item+" Value of ="+person[item]);
 }

2. Add attributes to json objects dynamically

Need to use the person object in 1


var copyPerson={}  // Create copyPerson Object, setting the person Attributes in include methods copy To the object 
 for(var item in person){
 copyPerson[item]= person[item];  // So that the loop can set the person Attributes in include methods copy To copyPerson Win 
 }
 
 for(var item in copyPerson){
 alert("copyPerson Medium "+item+" Value of ="+person[item]);
 }

Note: Using Ext. apply (copyPerson, person), you can also include all properties in person into methods copy into copyPerson

3. Traverse the properties of ordinary js objects


// Definition 1 An ordinary one js Class containing methods 
 var p= function (){
 this.name= ' Li 4';
 this.pass= '456';
 this.fn= function(){
  alert(this.name+" Password of ="+this.pass);
 }
 
 }

 var pp= new p();  // Generate 1 A p Objects of the class  pp
 
 for(var item in pp){
 
 // Traversal pp Object, showing only the properties in the   Non-functional   Attribute, note that you cannot   Traversal  p This class 
 if(typeof(pp[item])== "function")
  continue;
 alert("p Object "+item+" Properties of ="+pp[item]);
 }

Ordinary js objects can also be copy, copy methods and 2. Dynamic json objects add attributes ideas 1.


Related articles: