#stringify outputting an empty property

1 messages · Page 1 of 1 (latest)

pure creek
#

i have an object that i want to stringify. when i print the object using console.log, everything comes up normal without any issues

{
  player: "Test",
  items: [
    'Stylish': { items: [Object] },
    'Gas': { items: [Object] },
    'Polished': { items: [Object] },
    'Featherweight': { items: [Object] },
  ],
}

When i call JSON.stringify on the object the items array turns up blank though, how can i fix this?

north yacht
winged void
#

yeah, that's the issue

#

console.log pretty-prints the object, it doesn't encode it

#

that includes non-index keys on arrays

pure creek
#

I was wondering that too-- would it come out that way if i assigned values to it using items[key] = value or would i have to use items.push()

winged void
#

well, what do you want it to do

#

should items be keyed or indexed?

pure creek
#

keyed

winged void
#

then it should be a plain object, not an array

#

or a map, but that's not directly serializable as json

pure creek
winged void
#

[] = array, indexed, list
{} = (plain) object, keyed, record/dict

#

how you put stuff on/in items doesn't matter too much; what matters is what items itself is

pure creek
#

I know you can assign a type to an array in an interface, but is it possible to do so with something like a keyed object

winged void
#

not sure what you mean by that

#

do you mean the contents of the array/object

pure creek
#

Yeah

winged void
#

that's what Record is for

#

!hb record

solemn quarryBOT
winged void
#

or an index signature, but using Record<string, V> is pretty much an index signature

#

T[] ~ { [key: string]: T }
readonly T[] ~ { readonly [key: string]: T }
Array<T> ~ Record<string, T>
ReadonlyArray<T> ~ Readonly<Record<string, T>>

pure creek
#

oh i found the issue

#

i was getting an instance of the object that had items as an array and not an object

#

thanks for your help