1

I wouldn't normally do it this way but its for a practice exercise to convert an object without using JSON.stringify(). The object to convert is below:

obj = {
  num: 0,
  string: "string",
  func: function () {},
  emptyString: '',
  null: null,
  undefined: undefined
};

It should produce the answer below:

'{"num":0,"string":"This is a string","emptyString":"","null":null}'
2
  • 1
    There are many JSON.stringify polyfills around. Just look at them to gain the insight.
    – Bergi
    Sep 29, 2018 at 21:52
  • 1
    JSON.stringify does a lot of things. Which in particular do you have problems with? Please ask a more specific question about what part you do not understand.
    – Bergi
    Sep 29, 2018 at 21:53

2 Answers 2

0

Of course you will always want to use JSON.Stringify(), but for the sake of exercise:

obj = {
  num: 0,
  string: "string",
  func: function () {},
  emptyString: '',
  null: null,
  undefined: undefined
};

str = Object
        .entries(obj)
        .reduce((a, e) => {
          if (typeof e[1] != "function") {
            a += `"${e[0]}" : "${e[1]}", `;
          }
          return a;
        }, "`{")
        .slice(1, -2) + "}`";

console.log(str)
2
  • This doesn't escape any property keys or string values.
    – Bergi
    Sep 29, 2018 at 21:52
  • undefined is not the same as "undefined", and [1, 2, 3] will also not work. Sep 29, 2018 at 21:54
0
    var str = Object
    .entries(input)
    .reduce((a, e) => {
      if (typeof e[1] != "function" && e[1] !== undefined) {
        if(e[0] === "num" || e[0] === "null"){
          a += `"${e[0]}":${e[1]},`;
        } else{
        a += `"${e[0]}":"${e[1]}",`;
      }
      }
      return a;
    }, "`{")
    .slice(1, -1) + "}";
return str;

was able to get it with the above...though I'm sure there is a better answer. I learned that "polyfills" are what I needed to search around for from the user Bergi.

Thanks everyone who helped out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.