Skip to content

Instantly share code, notes, and snippets.

@jiangtao
Created August 10, 2017 03:46
Show Gist options
  • Save jiangtao/cfad3e4c877e63b23f0c25cfae3c267a to your computer and use it in GitHub Desktop.
Save jiangtao/cfad3e4c877e63b23f0c25cfae3c267a to your computer and use it in GitHub Desktop.
simple uri object setter and getter
const PATH = require('path')
function set(obj, path, value) {
let keys = PATH.normalize(path).split('/').filter(Boolean)
let k
while(keys.length) {
k = keys.shift()
if(!obj[k] || typeof obj[k] != 'object') {
obj[k] = keys.length == 0 ? value : {}
}
obj = obj[k]
}
return value
}
function get(obj, path) {
let keys = PATH.normalize(path).split('/').filter(Boolean)
return keys.reduce((v, key) => {
return v[key]
}, obj)
}
const data = {
"menu": {
"id": 123,
"list": [0, 1, 2, 3, 4],
"popup": {
"menuitem": [
{
"value": "New",
"onclick": "CreateNewDoc()"
},
{
"value": "Open",
"onclick": "OpenDoc()"
},
{
"value": "Close",
"onclick": "CloseDoc()"
}
]
}
}
}
let obj = {}
// console.log(get(data, '/menu/id/'))
// console.log(get(data, '/menu/popup/menuitem/0/value/'))
// console.log(get(data, '/menu/popup/menuitem/0/value/../../'))
set(obj, '/a/b', 'a')
console.log(obj)
console.log(get(obj, 'a/b/'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment