Object to Y.Map

I have a complex object in my application as store for managing all the state of the page. I want use yjs to make the page change sync for different user.
Firstly, it seems I have to covert the object to y.Map, is there any tool function like ymap.fromJSON()? Or should I make a recursion to convert it. Or event I should not do it in this way?
Sorry for this stupid question, I am new to CRDT.

I’m a rookie here trying to understand some of the same things. I think the answer is here:

From this thread: One large Y.Doc or many smaller Y.Doc? - #2 by ViktorQvarfordt

@njleonzhang I don’t believe that exists, but you could do something like this:

const deepSharedMap = obj => {
  if (typeof obj !== ‘object’) return obj
  const map = new Y.Map()
  Object.entries(obj).forEach(([key, value]) =>
    map.set(key, 
      Array.isArray(value) ? new Y.Array(value.map(deepSharedMap)) ?
      : deepSharedMap(value) 
    )
  )
  return map
}

That would be adequate for a one-time conversion, however I would be wary of trying to re-hydrate or update a shared type with this approach. It’s better to treat the shared type as the source of truth and access it directly in modules or components.

1 Like

There is no api to just convert an object into a map. And infact don’t expect a reasonably complex object to magically map to a Y.Doc. When trying to take an existing object, and model it as a Y document, you should carefully look at your original object and see how you can map it.

Every ydoc must contain at least one shared data type (Y.Array, Y.Map etc), but could contain multiple shared data types. Each of these shared types are top level (or root level) data types that can store data as well as references to other Y documents.

You will need to decide how your ydoc will be structured and how many and what type of shared types you will need to use. And then write your logic to convert your object to Ydoc and vise-a-versa.