Created
October 20, 2021 10:00
-
-
Save fidelthomet/034124aeb7ebce1ca5834a8d16e74172 to your computer and use it in GitHub Desktop.
@-signs in javascript object keys are tedious to work with as they can't be accessed through dot notation or unpacked using the destructuring assignment. Yet @ is used in formats like JSON-LD. This script contains two methods to recursively replace @ with $ at the start of object keys.
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
function atTo$(data) { | |
if (Array.isArray(data)) { | |
return data.map(d => atTo$(d)) | |
} else if (typeof data === 'object' && data != null) { | |
return Object.fromEntries(Object.entries(data).map(d => { | |
d[0] = d[0].replace(/^@/, '$') | |
return atTo$(d) | |
})) | |
} | |
return data | |
} | |
function atFrom$(data) { | |
if (Array.isArray(data)) { | |
return data.map(d => atFrom$(d)) | |
} else if (typeof data === 'object' && data != null) { | |
return Object.fromEntries(Object.entries(data).map(d => { | |
d[0] = d[0].replace(/^\$/, '@') | |
return atFrom$(d) | |
})) | |
} | |
return data | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment