Last active
May 13, 2016 00:54
-
-
Save agusputra/43d373dc3ec883688f3a4af1d7ebdf29 to your computer and use it in GitHub Desktop.
Access or Compose object using string literal. ex: '1.2.3' => {"1": {"2": {"3": "0"}}}
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 'use strict'; | |
| const state = { | |
| a: { | |
| aa: { | |
| aaa: 'AAA' | |
| }, | |
| ab: { | |
| aab: 'AAB' | |
| } | |
| } | |
| }; | |
| function accessObject(context, properties, value) { | |
| properties = properties.split('.'); | |
| let head = context; | |
| context = head; | |
| for (let i = 0; i < properties.length; i++) { | |
| if (i === properties.length - 1) { | |
| context[properties[i]] = value; | |
| break; | |
| } | |
| context = context[properties[i]]; | |
| } | |
| return head; | |
| } | |
| function composeObject(properties, value) { | |
| properties = properties.split('.'); | |
| let head = {}; | |
| let context = head; | |
| for (let i = 0; i < properties.length; i++) { | |
| if (i === properties.length - 1) { | |
| context[properties[i]] = value; | |
| break; | |
| } | |
| context = context[properties[i]] = {}; | |
| } | |
| return head; | |
| } | |
| const result1 = accessObject(state, 'a.aa.aaa', 'foo'); | |
| const result2 = composeObject('a.aa.aaa', 'foo'); | |
| console.log(JSON.stringify(result1, null, 1)); | |
| console.log(JSON.stringify(result2, null, 1)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment