在 react-native 中将嵌套的领域对象转换为 json

Lin*_*ang 5 javascript realm react-native

我在我的 react-native 应用程序中定义了嵌套的领域对象:

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',
  }
}
Run Code Online (Sandbox Code Playgroud)

当我User从领域查询时,我想将其转换为 Json 并通过 http 请求发送到后端服务器。但是,在搜索将领域对象转换为 Json 的模块后,我没有找到任何有用的内容来完成这项特定任务。如果有人知道在 react-native 中将嵌套领域对象转换为 Json 的简单方法,我将不胜感激。

Jér*_*rin 3

Realm 目前还没有在他的 api 中集成这种功能,但是你可以尝试这样的事情:

function realmToPlainObject(realmObj) {
  return JSON.parse(JSON.stringify(realmObj));
}
Run Code Online (Sandbox Code Playgroud)

或者像那样,但是会很慢!:

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

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

  return object;
});
Run Code Online (Sandbox Code Playgroud)

我知道这可能是多余的,但更好的方法是通过在您的realmObject中获取您想要的每个键来创建json对象。

  • 这实在是太不舒服了 (2认同)