Skip to content

Instantly share code, notes, and snippets.

@multivoltage
Created May 21, 2020 19:52
Show Gist options
  • Save multivoltage/c00e42517a71cfde1e793cf3efb5e6d1 to your computer and use it in GitHub Desktop.
Save multivoltage/c00e42517a71cfde1e793cf3efb5e6d1 to your computer and use it in GitHub Desktop.
Take any object (null,undefined string boolean object array...) and return same object with some new values based on some rules
// my backend return all date in a UTC format without "Z" at the end of string. I want to add a "Z" for all data that contain a date
// from "2020-05-21T19:51:25.396" to "2020-05-21T19:51:25.396Z"
const object: any = {
name: "-",
created_at: "-",
created_when: "-",
calendar: {
updated_at: "-",
},
arr: [1,2,{
aa_at: "-"
}]
}
const arr = [
object,
object
]
function isPrimitive(test: any): boolean {
return (test !== Object(test));
};
function remapObject(original: any){
if(isPrimitive(original)){
return original
}
if(Array.isArray(original)){
return original.map(remapObject)
} else {
return Object.keys(original).reduce((acc,currentFieldName) => {
const value = original[currentFieldName]
if(isPrimitive(value)){
if(typeof value === "string" && currentFieldName.endsWith("_at")){
acc[currentFieldName] = value+"Z"
} else {
acc[currentFieldName] = value
}
} else {
// array of object
if(Array.isArray(value)){
acc[currentFieldName] = value.map(remapObject)
} else {
acc[currentFieldName] = remapObject(value)
}
}
return acc
},{})
}
}
console.log(remapObject(object))
console.log('xxxxxx')
console.log(remapObject(arr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment