const object = {
data: 11444,
package: 'dddEE5',
};
const objToString = (obj) => {
const result = [];
result.push('{');
for (const key in obj) {
if (typeof obj[key] === 'object') {
result.push(objToString(obj[key]));
}
result.push(` ${key}: ${obj[key]}`);
}
result.push('}');
return result;
};
objToString(object).map(key => console.log(key));
// {
// data: 11444
// cd: dddEE5
// }
const object = {
data: 11444,
cd: {
package: 'dddEE5',
},
};
objToString(object).map(key => console.log(key));
// {
// data: 11444
// cd: {
// package: 'dddEE5'
// }
// }
function objToString(val, tabSize = 2, depth = 0, noIndent = false) {
const indent = ' '.repeat(tabSize * depth);
return (noIndent ? '' : indent) + (
val instanceof Array
? `[\n${val.map(n => objToString(n, tabSize, depth + 1)).join(',\n')}\n${indent}]`
: val instanceof Object
? `{\n${Object
.entries(val)
.map(n => n.map((m, i) => objToString(m, tabSize, depth + 1, i)).join(': '))
.join(',\n')}\n${indent}}`
: typeof val === 'string'
? `"${val}"`
: val
);
}
console.log(objToString({
numbers: [ 69, 187, 666 ],
strings: [ 'hello, world!!', 'fuck the world', 'fuck everything' ],
falsy_values: [ 0, '', NaN, false, null, undefined ],
object: { xxx: true, yyy: Infinity, zzz: { '!&$': [ [ [ -1 ] ] ] } }
}));