简体   繁体   中英

Javascript nested objects to JSON: how to filter attributes

I have a hierarchy of JS Objects, like this:

function Obj1(){
    this.att1;
    this.Obj2Array;
}
function Obj2(){
    this.att1;
    this.att2;  
}

where Obj1 has a reference to an array of Obj2. As you can see Obj1 and Obj2 can have similar attribute names. no guarantee for uniqueness.

I want to get the JSON of Obj1, and I want to exclude some attributes of Obj2. I know that stringify receives a replacer function or array, And I have tried it but there is the following problem:

When I use a replacer function, how can I differentiate between attributes in Obj1 and Obj2, even if they have the same name? my final goal is to have a behavior like Java toString, where each Object gets to make a decision about its attributes:

Obj1.prototype.stringify = function (key, val){
    // if own attribute, return val;
    // else it is an Obj2 attribute, return Obj2.prototype.stringify(key, val)
}
Obj2.prototype.stringify = function (key, val){
    if (key == "att1"){
        return "";
    } else if (key == "att2"){
        return val;
    }
}

I suppose I am missing a better solution.

A good solution is using 'toJSON' function!

Just as Java's printing operation that calls toString, In Javascript, the JSON.stringify function calls the object's 'toJSON' function. A user defined toJSON function changes the behavior and you can pick each object's attributes. It goes like this:

Obj1.prototype.toJSON = function (){
    return {
        att1: this.att1,
        obj2array: this.Obj2Array
    };
}

Obj2.prototype.toJSON = function (){
    return {
        att2: this.att2
    };
}

for using it:

var o1 = new Obj1;
// assign anything you want to o1...
JSON.stringify(o1);

Reading your code i think that you want keep attributes from Obj1 and only get non existent attributes for Obj2. You can do that with assign method in the next way:

var Obj1 = {
    attr1: 'foo'
};

var Obj2 = {
    attr1: 'foo2',
    attr2: 'bar'
};
// now, c has attr1: 'foo' (from Obj1) and attr2: 'bar' (from Obj2)    
var c = Object.assign({}, Obj2, Obj1);

// and finally call json stringify with new object
JSON.stringify(c);

With Object.assign you can clone or merge objects: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/assign

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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