I'm trying to stringfy an object with my custom function, I just do it for practice purposes. But the function doesn't return what I want.
Here is the whole function and the object I pass into.
const data = { hello: "world", is: true, nested: { count: 5 } };
const stringify = (obj, symbol, numRepeat, stringifiedObj) => {
const keys = Object.keys(obj);
const values = Object.values(obj);
// console.log("stringified object when functino runs", stringifiedObj);
// console.log("ALL KEYS", keys);
// console.log("ALL VALUES", values);
keys.forEach((key, index) => {
// console.log(typeof obj[key]);
if (typeof values[index] !== "object") {
console.log(values[index]);
// console.log(`{${key}: ${values[index]}}`);
stringifiedObj += `${key}: ${values[index]}\n`;
console.log("strinbgify inside if".toLocaleUpperCase(), stringifiedObj);
} else {
console.log("this is Object", obj[key]);
stringify(obj[key], symbol, values, stringifiedObj);
}
});
return `{${stringifiedObj}}`;
};
console.log("FUNCTION RETURN", stringify(data, "|-", 2, ""));
You can ignore symbol and numrepeat parameters since I will use them later.
so the expected result is
hello: world
is: true
nested:{
count: 5
}
but it returns;
hello: world
is: true
where am I doing wrong?
stringifyreturns something, but you completely ignore the return value in the recursive call. But also, you useforEachwhich ignores return values in general, so even areturn stringify(…)won’t fix it. You should use a differentArraymethod.stringifiedObjin this call:stringifiedObj +=${key}: ${values[index]}\n;Inside a single call that's not a problem, but in the recursive call, it is ignored because you don't return and use that value.