Last active
March 4, 2020 14:07
-
-
Save ibrahimgunduz34/2a30e15c52838b4a463138358a8bdeef to your computer and use it in GitHub Desktop.
Setting value to a complex object field by giving the object key as string
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
| function propertyAccess(obj, key, value) { | |
| const sKey = key.replace(/\[/gi, '.').replace(/\]/gi, '').split('.') | |
| const current = sKey[0] | |
| const next = sKey.slice(1).join('.') | |
| if (sKey.length != 1) { | |
| return propertyAccess(obj[current], next, value) | |
| } | |
| if (value !== undefined) { | |
| obj[key] = value | |
| } | |
| return obj[key] | |
| } | |
| //--- Main ---- | |
| const myObject = { | |
| catalog: { | |
| products: [ | |
| { | |
| id: 1, | |
| name: 'Shirt' | |
| }, | |
| { | |
| id: 2, | |
| name: 'Jacket' | |
| } | |
| ] | |
| } | |
| } | |
| console.log( propertyAccess(myObject, 'catalog.products[1].id') ) // 2 | |
| propertyAccess(myObject, 'catalog.products[1].id', 3) | |
| console.log( propertyAccess(myObject, 'catalog.products[1].id') ) // 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment