Skip to content

Instantly share code, notes, and snippets.

@tuantvk
Last active August 16, 2021 10:20
Show Gist options
  • Save tuantvk/7452a9ca10b2502ca13776f41c94dfbc to your computer and use it in GitHub Desktop.
Save tuantvk/7452a9ca10b2502ca13776f41c94dfbc to your computer and use it in GitHub Desktop.
Format object values to object string
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