有没有办法将 Ember 对象转换为普通的 javascript 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15001409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:06:06  来源:igfitidea点击:

Is there any way to convert Ember Object into plain javascript object?

javascriptember.js

提问by Qrilka

I could not find any way to accomplish the task of such conversion as I could not find any means of getting Ember.js properties for the object. Ember.keysreturns only the properties I set in createor with getand the properties declared in Ember.extenddo not show up there. I use such properties to set up default values (e.g. []for array properties)

我找不到任何方法来完成这种转换任务,因为我找不到任何获取对象的 Ember.js 属性的方法。Ember.keys仅返回我在create其中设置或使用get的属性,并且在其中声明的属性Ember.extend不显示在那里。我使用这些属性来设置默认值(例如[]数组属性)

采纳答案by Qrilka

At the moment I solve it with the following snippet:

目前我用以下代码段解决了它:

App.plainCopy = function (obj) {
  if (Ember.isArray(obj)) {
    return obj.map(App.plainCopy);
  } else if (typeof(obj) === "object") {
    if (App.Plainable.detect(obj)) {
      return obj.plainCopy();
    } else {
      throw new Error(Ember.String.fmt("%@ is not Plainable", [obj]));
    }
  } else {
    return obj;
  }
}

App.Plainable = Ember.Mixin.create({
  plainCopy: function() {
    var props = Ember.keys(this);
    var proto = this.constructor.prototype;
    for(p in proto) {
      if (proto.hasOwnProperty(p) && typeof(this[p])!=="function") {
        props.push(p);
      }
    }
    var copy = {};
    props.forEach(function(p) {
      copy[p] = App.plainCopy(this.get(p));
    }, this);
    return copy;
  }
});

It does not go up the class hierarchy and does not look into mixins (as I use for data objects which are quite simple form that point of view)

它不会上升到类层次结构,也不会查看 mixins(因为我用于数据对象,这些数据对象的形式非常简单)

回答by user10078

Here is my dirty workaround

这是我肮脏的解决方法

var newModel = JSON.parse(JSON.stringify(model));

回答by Wildhoney

I would do something similar to the person above, but I'd do it a little bit differently.

我会做与上面那个人类似的事情,但我会做一些不同的事情。

Mixin

混入

App.NativeObject = Ember.Mixin.create({
    toNative: function() {
        var properties = [];
        for (var key in this) {
            if (jQuery.inArray(Ember.typeOf(object[key]), ['string', 'number', 'boolean']) !== -1) {
                properties.push(key);
            }
        }
        return this.getProperties(properties);
    }
});

Object

目的

Then you just need to implement the App.NativeObjectmixin in your objects that you would like the toNativeon:

然后你只需要App.NativeObject在你想要的对象中实现mixin toNative

var Object = Ember.Object.extend(App.NativeObject, {
    name: 'Adam',
    count: 4
});

We then have the toNativemethod on all the objects that implement our mixin.

然后我们toNative在实现我们的 mixin 的所有对象上都有这个方法。

Obligatory jsFiddle: http://jsfiddle.net/jumUx/

强制性 jsFiddle:http: //jsfiddle.net/jumUx/

回答by Mark Fox

If your object is a subclass of ember-data model notice you can use the toJSONmethodotherwise you can use:

如果您的对象是 ember-data 模型通知的子类,您可以使用该toJSON方法,否则您可以使用:

JSON.parse(JSON.stringify(emberObj))

To grab any values which support native json serialization (i.e. not functions/methods)

获取任何支持原生 json 序列化的值(即不是函数/方法)

回答by ecairol

This worked for me:

这对我有用:

myModel.toJSON({includeId: true})

myModel.toJSON({includeId: true})

I'm using Ember 3.

我正在使用 Ember 3。

回答by voodoologic

With modern (3.17) ember, I've used myEmberObject.getProperties('id', 'name', 'foo', 'bar')

使用现代 (3.17) 余烬,我使用过 myEmberObject.getProperties('id', 'name', 'foo', 'bar')

It produces a plain object.

它产生一个普通对象。

回答by Jaime

This is what I did and it works quite well. Note, this should be ready only, as any changes to an object or array in the copied object will affect the original object

这就是我所做的,并且效果很好。请注意,这应该只准备好,因为对复制对象中的对象或数组的任何更改都会影响原始对象

App.BaseValidations = Ember.Object.create({
    toObject: function() {
        var destination = {}
        for (var k in this) {
            if (this.hasOwnProperty(k) && typeof(this[k]) !== 'function') {
                destination[k] = this[k];
            }
        }
        return destination;
    }
})

回答by utopman

something quite simple that worked properly enough for me is :

对我来说足够正常的非常简单的事情是:

Ember.Object.reopen({
    toJson: function() {
        return JSON.parse(JSON.stringify(this));
    }
});

at app loading time.

在应用加载时。

回答by bargar

Another possible solution that may suit your needs while not being fully recursive for nested Ember objects:

另一种可能的解决方案可能适合您的需求,但不能完全递归嵌套 Ember 对象:

// where myEmberObject is.. an ember object
var plainJavaScriptObject = myEmberObject.toJSON();

This will only include actual properties that you've defined and no Ember internals. Again, the drawback here is that any nested Ember objects will not, themselves, be converted but will appear as Strings in style of "".

这将仅包括您定义的实际属性,而不包括 Ember 内部结构。同样,这里的缺点是任何嵌套的 Ember 对象本身不会被转换,而是会以“”的样式显示为字符串。