繁体   English   中英

从对象数组中创建JSON JavaScript

[英]Make json from array of objects javascript

我有一个具有许多属性和方法的javascript对象,我希望将其发送到php文件。 为此,我想将其转换为Json数据。

但是由于复杂对象的类,我只是不明白应该如何使用json.stringify来做到这一点。

对象看起来像这样。 我有一系列必须通过ajax发送的对象。

此外,此类还具有其他对象数组作为属性,以及一堆其他方法。

var PhotoFile = function(clientFileHandle){
     PhotoFile.count = PhotoFile.count  + 1;
        this.specificClass = "no-" + PhotoFile.count;
        this.checkbox = null;
        this.attributes = [];
        this.file = clientFileHandle;
        this.fileExtension = null;
        //meta data
        this.meta = null;
        this.orientation = null;
        this.oDateTime = null;
        this.maxWidth = 150;
        this.maxHeight = 100;
        //raw data
        this.imgData = null;
        this.imgDataWidth = null;
        this.imgDataHeight = null;
        this.checkSum1 = null;
        this.checkSum2 = null;
        //DOM stuff
        this.domElement = null;
        this.imgElement = null;
        this.loadProgressBar = null;
        this.uploadProgressBar = null;
        this.imageContainer = null;
        this.attributeContainer = null;
        this.indexInGlobalArray = -1;
        //flags
        this.metaLoaded = false;
        this.startedLoading = false;
        this.finishedLoading = false;
        this.needsUploading = true;

        this.imageDisplayed = false;
        //listeners
        this.onFinishedLoading = function () {};
        this.onFinishedUploading = function () {console.log('Called default end '+this.file.name)};
    ..... plus other methods.
    }

您可以在对象上创建一个函数,该函数返回对象的可序列化表示形式。

例如

function SomeObject() {
    this.serializeThis = 'serializeThis';
    this.dontSerializeThis = 'dontSerializeThis';
}

SomeObject.prototype.toSerializable = function () {
    //You can use a generic solution like below
    return subsetOf(this, ['serializeThis']);

    //Or a hard-coded version
    // return { serializeThis: this.serializeThis };
};

//The generic property extraction algorithm would need to be more complex
//to deep-filter objects.
function subsetOf(obj, props) {
    return (props || []).reduce(function (subset, prop) {
        subset[prop] = obj[prop];
        return subset;
    }, {});
}


var o = new SomeObject();

JSON.stringify(o.toSerializable()); //{"serializeThis":"serializeThis"}

请注意,使用通用属性提取器算法将迫使您泄漏实现细节,因此会违反封装,因此尽管使用此方法实现解决方案可能会更短,但在某些情况下可能不是最佳方法。

但是,有一点是,通常可以做到限制内部泄漏是实现财产干将

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM