Skip to content

Instantly share code, notes, and snippets.

@fidelthomet
Created October 20, 2021 10:00
Show Gist options
  • Save fidelthomet/034124aeb7ebce1ca5834a8d16e74172 to your computer and use it in GitHub Desktop.
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.
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