从真实数据库获取父模型数据时,如何将相关模型数据转换为Array?

时间:2018-08-07 10:07:58

标签: javascript arrays react-native realm realm-mobile-platform

我在领域db中有一个架构,其中数据来自不同模型到父模型。

我能够通过执行

将从父模型获得的数据转换为Array。
static get() {
    let result = realm.objects(this.schema.name)
    return result.map(x => Object.assign({}, x))
}

以下是父模型中的数据示例

[
{"deal_id":"d001","product_id":"p001",
"user_defined_attributes":{"0":{"name":"Color","value":"Red"},"1":{"name":"Quality","value":"NO.1"}},
"deal_channels":{"0":{"channel_id":"d001_u00001_u00002","to_user_id":"u00002","deal_id":"d001",
"chat_messages":{"0":{"message_id":"m1","channel_id":"d001_u00001_u00002","time_stamp":1533548036,"sendor_id":"u00001","storage_status":"active","status":"seen"}}}}
]

如何将“ user_defined_attributes”,“ deal_channels”中的数据然后再将““ chat_messages””中的数据转换为Array。

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码转换给定的JSON对象。

var obj =  obj[0];
var convert = (o) => Object.keys(o).map(k => o[k]);
obj.user_defined_attributes = convert(obj.user_defined_attributes)
obj.deal_channels = convert(obj.deal_channels).map(d => {
   d.chat_messages = convert(d.chat_messages);
   return d;
});