0

I would like to recursively iterate through an object to create one array with all the keys and value pairs in the top level using javascript.

The function would take the following:

obj1 = { name: "Goggles", price: 1499, obj: {no: "hi", yes: "bye"} }

and convert it into this:

{ name: "Goggles", price: 1499, no: "hi", yes: "bye" }

I am using Object.keys(obj1).length to tell whether or not a property has a value containing multiple properties. The problem is that when it sees a string as a value, it treats it as an Object with each character representing a value:

Object.keys(obj).length, where obj == name: "Goggles"

retruns 7

this is because Object.keys(...)length interprets it as {0: G, 1: o, 2: g, 3: g, 4: l, 5: e, 6: s}

Is there a way to differentiate Objects that have multiple key/value pairs from those that don't? Specifically from a key with a value that happens to be a String.

D'errah
  • 29
  • 1
  • 4
  • This question is phrased very strangely. You just want to test whether a variable holds a string or an object, not whether an object has 1 or 0 keys. Use `typeof`. It makes no sense to use `Object.keys` on a string, strings are not "objects with string values", they're *strings*. – user229044 Jan 05 '23 at 01:58
  • Correct, I just wanted to test whether a variable held a String of an object. Also correct, typeof ended up doing just that. For the title, I should have used *properties* with String values. Because, as described in the actual question, the way I was attempting to accomplish my task was by looking at an key's corresponding value, and checking to see if it had multiple properties. I don't believe my question was phrased "very strangely" at all, but I do agree my title was technically incorrect. And yes, strings are not "objects with string values" but they are objects with character values. – D'errah Jan 05 '23 at 22:53

0 Answers0