Created
August 28, 2021 03:17
-
-
Save zazaulola/324a21f8407bd8687853c6c9cd74f233 to your computer and use it in GitHub Desktop.
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 at(obj, path, val = undefined) { | |
// If path is an Array, | |
if (Array.isArray(path)) { | |
// it returns the mapped array for each result of the path | |
return path.map((path) => at(obj, path, val)); | |
} | |
// Uniting several RegExps into one | |
const rx = new RegExp( | |
[ | |
/(?:^(?:\.\s*)?([_a-zA-Z][_a-zA-Z0-9]*))/, | |
/(?:^\[\s*(\d+)\s*\])/, | |
/(?:^\[\s*'([^']*(?:\\'[^']*)*)'\s*\])/, | |
/(?:^\[\s*"([^"]*(?:\\"[^"]*)*)"\s*\])/, | |
/(?:^\[\s*`([^`]*(?:\\`[^`]*)*)`\s*\])/, | |
] | |
.map((r) => r.source) | |
.join("|") | |
); | |
let rm; | |
while (rm = rx.exec(path.trim())) { | |
// Matched resource | |
let [rf, rp] = rm.filter(Boolean); | |
// If no one matches found, | |
if (!rm[1] && !rm[2]) { | |
// it will replace escape-chars | |
rp = rp.replace(/\\(.)/g, "$1"); | |
} | |
// If the new value is set, | |
if ("undefined" != typeof val && path.length == rf.length) { | |
// assign a value to the object property and return it | |
return (obj[rp] = val); | |
} | |
// Going one step deeper | |
obj = obj[rp]; | |
// Removing a step from the path | |
path = path.substr(rf.length).trim(); | |
} | |
if (path) { | |
throw new SyntaxError(); | |
} | |
return obj; | |
} | |
// Test object schema | |
let o = { a: { b: [ [ { c: { d: { '"e"': { f: { g: "xxx" } } } } } ] ] } }; | |
// Print source object | |
console.log(JSON.stringify(o)); | |
// Set value | |
console.log(at(o, '.a["b"][0][0].c[`d`]["\\"e\\""][\'f\']["g"]', "zzz")); | |
// Get value | |
console.log(at(o, '.a["b"][0][0].c[`d`]["\\"e\\""][\'f\']["g"]')); | |
// Print result object | |
console.log(JSON.stringify(o)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment