开发者

JSON.stringify ignore some object members

开发者 https://www.devze.com 2023-04-05 09:39 出处:网络
Heres a simple example. function Person() { this.name = \"Ted\"; this.age = 5; } persons[0] = new Person();

Heres a simple example.

function Person() {
  this.name = "Ted";
  this.age = 5;
}

persons[0] = new Person();
persons[1] = new Person();
JSON.stringify(persons);

If I have an array of Person objects, and I want to stringify them. How can I return JSON with only the name variable.

The reason for this is, I have large objects with recursive references that are causing problems. And I want to remove the re开发者_高级运维cursive variables and others from the stringify process.

Thanks for any help!


the easiest answer would be to specify the properties to stringify

JSON.stringify( persons, ["name"] )

another option would be to add a toJSON method to your objects

function Person(){
  this.name = "Ted";
  this.age = 5;      
}
Person.prototype.toJSON = function(){ return this.name };

more: http://www.json.org/js.html


If you're only supporting ECMAScript 5 compatible environments, you could make the properties that should be excluded non-enumerable by setting them using Object.defineProperty()[docs] or Object.defineProperties()[docs].

function Person() {
    this.name = "Ted";
    Object.defineProperty( this, 'age', {
        value:5,
        writable:true,
        configurable:true,
        enumerable:false // this is the default value, so it could be excluded
    });
}

var persons = [];

persons[0] = new Person();
persons[1] = new Person();

console.log(JSON.stringify(persons));  // [{"name":"Ted"},{"name":"Ted"}]


I would create a new array:

var personNames = $.map(persons,function(person){
  return person.name;
});
var jsonStr = JSON.stringify(personNames);


see this post specify the field you'd like to include. JSON.stringify(person,["name","Address", "Line1", "City"]) it is match better then what suggested above!

0

精彩评论

暂无评论...
验证码 换一张
取 消