Last active
May 16, 2018 15:04
-
-
Save qoomon/0758f4fd62cba6a779ebff92d1ef6add to your computer and use it in GitHub Desktop.
Set and get JSON values by path string.
This file contains 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
const splitPath = (path)=> { | |
return path | |
.replace(/\[([\d]+)\]/g, '.$1') // replace [0] with .0 | |
.replace(/\['([\w]+)'\]/g, '.$1') // replace ['x'] with .x | |
.replace(/\["([\w]+)"\]/g, '.$1') // replace ["x"] with .x | |
.split('.'); | |
}; | |
const getPathValue = (object, path) => { | |
const pathSegments = splitPath(path); | |
pathSegments.forEach(pathSegment => { | |
object = object[pathSegment]; | |
}); | |
return object; | |
}; | |
const setPathValue = (object, path, value) => { | |
const pathSegments = splitPath(path); | |
var key; | |
var objectTemp = object; | |
pathSegments.forEach(pathSegment => { | |
object = objectTemp; | |
key = pathSegment; | |
objectTemp = objectTemp[key]; | |
}); | |
object[key] = value; | |
return value; | |
}; | |
Object.prototype.path = function(path, value){ | |
if(value) { | |
return setPathValue(this, path, value); | |
} else { | |
return getPathValue(this, path); | |
} | |
}; | |
// examples | |
foo = { | |
bar: { | |
buzz: 0 | |
}, | |
fizz: [ | |
{ | |
bar: 0 | |
} | |
] | |
}; | |
console.log(foo.path('bar.buzz',1)); | |
console.log(foo.path('bar.buzz')); | |
console.log(foo.path('fizz[0].bar',2)); | |
console.log(foo.path('fizz[0].bar')); | |
console.log(foo.path("fizz[0]['bar']",3)); | |
console.log(foo.path("fizz[0]['bar']")); | |
console.log(foo.path("",4)); | |
console.log(foo.path("")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment