Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert nested realm object to json in react-native

I have nested realm object defined in my react-native app as:

export const userSchema = {
  name: 'User',
  primaryKey: 'id',
  properties: {
    id: 'string',
    user_id: 'string',
    password: 'string',
    demographics: 'Demographics',
    notes: 'string'
  }
}

export const demographicsSchema = {
  name: 'Demographics',
  primaryKey: 'id',
  properties: {
    id: 'int',
    age: 'int',
    height: 'float',
    weight: 'float',
    gender: 'int',
  }
}

When I queried User from realm, I want to convert it to Json and send to backend server via http request. However, after searching for modules to convert realm object to Json, I didn't find any helpful content to do this sepecific task. If anyone knows a simple way to convert nested realm object to Json in react-native, I would be appreciated.

like image 630
RandomEli Avatar asked Oct 17 '22 21:10

RandomEli


1 Answers

Realm doesn't integrate this kind of function in his api at this time, but you can try something like this:

function realmToPlainObject(realmObj) {
  return JSON.parse(JSON.stringify(realmObj));
}

Or like that, but it will be really slow! :

var plainResults = Array.prototype.map.call(resultsCars, (car) => {
  var object = {};

  for (var property of YourSchema.properties) {
    object[name] = car[name];
  }

  return object;
});

I know that can be redundant, but a better way would be to create the json object by getting each key you want in your realmObject.

like image 79
Jérémy Magrin Avatar answered Oct 21 '22 06:10

Jérémy Magrin