Created
June 19, 2021 10:40
-
-
Save julienetie/547ddcfad742d7e4de5fdc3410349190 to your computer and use it in GitHub Desktop.
Object Path
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 objectPath = { | |
/* | |
Creates an object-path and assigns the value. | |
- object - object - The object to create the path onto | |
- stringLocation - string - The object path as a string. | |
- value - * - The value to assign. */ | |
assign (object, stringLocation, value) { | |
const locationList = stringLocation.split(dot) | |
const locationListLength = locationList.length | |
let acc = object | |
for (let i = 0; i < locationListLength; i++) { | |
const path = locationList[i] | |
if (i === locationListLength - 1) { | |
acc[path] = value | |
return | |
} | |
acc = acc[path] | |
} | |
}, | |
get (object, stringLocation) { | |
const locationList = stringLocation.split(dot) | |
const locationListLength = locationList.length | |
let acc = object | |
for (let i = 0; i < locationListLength; i++) acc = acc[locationList[i]] | |
return acc | |
}, | |
create (object, stringLocation, value) { | |
const locationList = stringLocation.split(dot) | |
const locationListLength = locationList.length | |
let acc = object | |
for (let i = 0; i < locationListLength; i++) { | |
const path = locationList[i] | |
if (!hasKey(acc, 'path') || acc[path] === undefined) { | |
if (i === locationListLength - 1) { | |
acc[path] = value === undefined ? null : value | |
return | |
} | |
acc = acc[path] = {} | |
} | |
} | |
}, | |
remove (object, stringLocation) { | |
objectPath.assign(object, stringLocation, undefined) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment