Js recursively converts package names to Corresponding Hierarchical objects c

Source: Internet
Author: User

Js recursively converts package names to Corresponding Hierarchical objects c

Example: The original object {a: {test: 1, B: 2} is based on. b. c. d To: {a: {test: 1, B: {c: {d :{}}}}}

Note: The package name is available. the json object itself is composed of attributes and values and can be nested. Therefore, there is a requirement to convert the package description string to the json type, note other existing attributes. in this example, the value of attribute a is an object. Therefore, you only need to extend the content of attribute B, and the value of attribute B is not an object type. Therefore, the object must be overwritten, other non-existent attributes should be paid to empty objects.

This example uses recursion:

 

Function namespace (oNamespace, sPackage) {var obj = oNamespace; var pkg =; if (sPackage. indexOf (.) =-1) {pkg = sPackage;} else {pkg = sPackage. substr (0, 1);} if (pkg &&! (Obj [pkg] & obj [pkg] instanceof Object) {obj [pkg] ={};} if (sPackage. indexOf (.)! =-1) {namespace (obj [pkg], sPackage. substr (2);} return obj ;}
Test code:

 

 

Var obj = namespace ({a: {test: 1, B: 2 }}, 'a. b. c. d'); console. log (JSON. stringify (obj ));

Result:

 

 

{A: {test: 1, B: {c: {d :{}}}}}

 

 



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.