problems(js): add “2633. Convert Object to JSON String”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
988f8fb927
commit
799bc6f803
1 changed files with 25 additions and 0 deletions
25
problems/js/convert-object-to-json-string.js
Normal file
25
problems/js/convert-object-to-json-string.js
Normal file
|
@ -0,0 +1,25 @@
|
||||||
|
/**
|
||||||
|
* @param {any} object
|
||||||
|
* @return {string}
|
||||||
|
*/
|
||||||
|
var jsonStringify = function(object) {
|
||||||
|
switch (typeof object) {
|
||||||
|
case 'boolean':
|
||||||
|
case 'number':
|
||||||
|
return `${object}`;
|
||||||
|
case 'string':
|
||||||
|
return `"${object}"`;
|
||||||
|
case 'object':
|
||||||
|
if (Array.isArray(object)) {
|
||||||
|
return `[${object.map(jsonStringify).join(',')}]`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (object) {
|
||||||
|
let nested = Object.keys(object).map(key => `"${key}":${jsonStringify(object[key])}`);
|
||||||
|
return `{${nested.join(',')}}`;
|
||||||
|
}
|
||||||
|
return 'null';
|
||||||
|
default:
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
};
|
Loading…
Reference in a new issue