What is an Ember way to convert extracted Ember Data records to simple objects?

I extracted a series of records using var items = store.find('model');. The returned object is an instance RecordArray, and contains multiple entries, each of which has Ember object that allows me to get and set properties of the record.

Everything looks good.

Now I need to pass the returned objects to a third-party library, and, of course, I can not send Ember objects there, since it expects simple objects.

I have looked at the pages and pages of related materials, but I cannot find a general way to do this. I am pretty sure that there is one, as this seems to be a very simple use case, so I don’t want to invent a wheel and write everything again.

Is there an object in Amber for this? How can I get a simple array with regular JavaScript objects (only hashes, I mean) from this RecordArraythat I got?

UPDATE

Of course, I can do it JSON.parse(JSON.stringify(recordArray));, but for large objects that don't seem too efficient with so many conversions. I am wondering if Ember makes a more direct way (with better performance) to do this.

Thank!

+4
source share
1 answer

As far as I know, there is no ObjectSerializer, so perhaps the easiest way is to use JSONSerializer and use JSON.parse to create objects from 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;
}
+2
source

Source: https://habr.com/ru/post/1543470/


All Articles