Fun JS methods, tiled JS objects

Source: Internet
Author: User

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.

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.