When thinking about filling HTML templates with JS objects, sometimes you may encounter nested objects, such:
VaR Person = { "Name": "Wang Chong" , "Age": 34 , "Sex": "male" , "Address" :{ "Area" :{ "Province": "Henan" , "City": "Zhengzhou" }, "Detail": "jinshui District No. 110" , "Zip": "400003"}, "Arr": [100,123 ], "Children" :[{ "Name": "Xiaohong", "Age": 6, "sex": "female" },{ "Name": "James", "Age": 3, "sex": "male" }]}
The template may be:
Name: {name}
Address: {address.area.province}, {address.area.city}, {address.zip}
The name should be replaced here, but the following is difficult for a while (in fact, I don't want to think about it !)
Today, I thought about it. It would be nice to pull the deep object value to the first layer! So, a method called "tile" came out!
Function Tiled (root, OBJ, keypre) {keypre = Keypre | ""; For ( VaR Key In OBJ) {subv = OBJ [Key]; VaR Newkey = "" ; If ( Typeof (Subv) = "object" ) {Newkey = Keypre! = ""? Keypre + "." + Key: Key; tiled (root, subv, newkey );} Else {Newkey = Keypre! = ""? Keypre + "." + Key: Key; root [newkey] = Subv ;}}}
Call method:
VaROBJ ={}; Tiled (OBJ, person );
Now obj is (in chrome ):
Used for the third question in a previous article.