JSON.stringify only includes the object's own, enumerable properties whose names are strings. So there are three ways for properties to be left out: If they're inherited, if they're non-enumerable (such as those Object.defineProperty creates by default), or if their names aren't strings (ES2015 has the ability for properties to have Symbol names rather than string names).
This demonstrates two of those, the "own" and "enumerable" aspects: It logs {"answer":42}, for instance, because obj only has one own, enumerable property, answer. prop is inherited, and foo is non-enumerable:
// An object to use as a prototype
var proto = {
prop: 1
};
// Create an object using that as its prototype
var obj = Object.create(proto);
// Define a non-enumerable property
Object.defineProperty(obj, "foo", {
value: 27
});
// Define an own, enumerable property
obj.answer = 42;
// Show the JSON for the object
snippet.log(JSON.stringify(obj));
This is in the specification for JSON.stringify:
Live Example:
// An object to use as a prototype
var proto = {
prop: 1
};
// Create an object using that as its prototype
var obj = Object.create(proto);
// Define a non-enumerable property
Object.defineProperty(obj, "foo", {
value: 27
});
// Define an own, enumerable property
obj.answer = 42;
// Show the JSON for the object
snippet.log(JSON.stringify(obj));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Just for completeness, this demonstrates Symbol-named properties being left out as well (live copy on Babel's REPL):
// An object to use as a prototype
var proto = {
prop: 1
};
// Create an object using that as its prototype
var obj = Object.create(proto);
// Define a non-enumerable property
Object.defineProperty(obj, "foo", {
value: 27
});
// Define an own, enumerable property with a string name
obj.answer = 42;
// Define an own, enumerable property with a Symbol name
var s1 = Symbol();
obj[s1] = "I'm enumerable and have a Symbol name";
// Show the JSON for the object
console.log(JSON.stringify(obj)); // {"answer":42}
// Proof that the Symbol property was enumerable comes
// from Object.assign
var obj2 = Object.assign(obj);
console.log(obj2[s1]); // I'm enumerable and have a Symbol name