Last active
August 16, 2021 10:20
-
-
Save tuantvk/7452a9ca10b2502ca13776f41c94dfbc to your computer and use it in GitHub Desktop.
Format object values to object string
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 formatToString(obj) { | |
let a = {}; | |
Object.entries(obj).forEach(([key, value]) => { | |
if (value) { | |
if ((Array.isArray(value) && value.length > 0) | |
|| (typeof value === "object" && Object.keys(value).length > 0) | |
|| (typeof value !== "object" && (String(value).length > 0)) | |
) { | |
a[key] = parseInt(value) === 0 ? '' : value; | |
} else { | |
a[key] = ""; | |
} | |
} else { | |
a[key] = ""; | |
} | |
}); | |
return a; | |
}; | |
// Example | |
console.log(formatToString({ | |
name: "", | |
age: 0, | |
age2: "0", | |
age3: 124, | |
age4: "124", | |
text: "hello", | |
arr: [], | |
arr2: ["t"], | |
isNull: null, | |
isUndefined: undefined, | |
obj: {}, | |
obj2: { a: 'name' }, | |
})); | |
// result | |
// { | |
// name: '', | |
// age: '', | |
// age2: '', | |
// age3: 124, | |
// age4: '124', | |
// text: 'hello', | |
// arr: '', | |
// arr2: [ 't' ], | |
// isNull: '', | |
// isUndefined: '', | |
// obj: '', | |
// obj2: { a: 'name' } | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment