Skip to content

Instantly share code, notes, and snippets.

@ibrahimgunduz34
Last active March 4, 2020 14:07
Show Gist options
  • Select an option

  • Save ibrahimgunduz34/2a30e15c52838b4a463138358a8bdeef to your computer and use it in GitHub Desktop.

Select an option

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
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