将检索到的Ember数据记录转换为纯对象的Ember方法是什么? [英] What is the Ember way of converting retrieved Ember Data records into plain objects?
问题描述
我使用 var items = store.find('model');
检索了一系列记录。返回的对象是一个 RecordArray
的实例,并包含几个条目,每个条目都有一个Ember对象,允许我将属性设置到记录中。
这一切看起来都不错。
现在我需要将返回的对象提供给第三方库,当然我也不能发送Ember对象在那里,因为它预期是普通的对象。
我查看了相关材料的页面和页面,但是我找不到任何通用的方法。我很确定有一个,因为这似乎是一个非常基本的用例,所以我不要
想要重新发明轮子,再写一次。
。在这个Ember里有一个设施吗?我如何从这个
RecordArray
获得一个简单的JavaScript对象数组(只是散列,我的意思是) 更新
当然我可以做 JSON .parse(JSON.stringify(recordArray));
,但是对于那些似乎没有太多转换的性能较差的大对象。我想知道Ember是否提供了更直接的方式(具有更好的性能)。
谢谢!
据我所知,没有ObjectSerializer,所以可能最简单的方法是使用JSONSerializer并使用JSON.parse从中创建对象。
items.map(function(e){
return JSON.parse(e.toJSON());
});
但是,您可以手动编写序列化逻辑。
function serializeToObject(model){
var fields = Ember.get(model.constructor,'fields');
obj = {};
fields.forEach(function(fieldName,kindOfField){
obj [fieldName] = model.get(fieldName);
});
return obj;
}
I have retrieved a series of records using var items = store.find('model');
. The returned object is an instance of RecordArray
, and contains several entries, each with an Ember object that allows me to get and set properties into the records.
It all looks pretty good.
Now I need to feed the returned objects into a third party library, and of course I cannot send Ember objects there since it expects plain objects.
I looked on pages and pages of related material but I can't find any generic way of doing this. I'm pretty sure there is one since this seems to be a very basic use case, so I don't want to reinvent the wheel and write it all again.
Is there a facility in Ember for that? How can I obtain a simple array with plain JavaScript objects (just hashes, I mean) from this RecordArray
I got?
UPDATE
Of course I can do JSON.parse(JSON.stringify(recordArray));
but for large objects that doesn't seem too performant with so many conversions. I'm wondering if Ember provides a more direct way (with better performance) of doing this.
Thanks!
As far as I know there is no ObjectSerializer so probably easiest way is to use JSONSerializer and use JSON.parse to create objects out of them.
items.map(function(e){
return JSON.parse(e.toJSON());
});
However, you can manually write serialization logic.
function serializeToObject(model){
var fields = Ember.get(model.constructor, 'fields');
obj = {};
fields.forEach(function(fieldName, kindOfField){
obj[fieldName] = model.get(fieldName);
});
return obj;
}
这篇关于将检索到的Ember数据记录转换为纯对象的Ember方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!