0

If I open this in a browser:

<!DOCTYPE html>
<html>
    <head>
        <title>Testing stringify</title>
    </head>
    <body>
        <script>
            var obj = {};
            var arr = [];
            arr.push(1,2);
            alert(arr); // 1,2
            Object.defineProperty(obj, "name", {
                value:arr
            });
            alert(obj.name); // 1,2
            alert(JSON.stringify(obj)); // {}
        </script>
    </body>
</html>

it will output what I've written in the comments. I don't understand why arr isn't included in the output JSON-string. Do I need to define some other properties on the descriptor object in defineProperty()? What am I doing wrong?

1 Answer 1

3

The property you made is non enumerable. Set enumerable: true in the descriptor and it'll work.

var obj = {};
var arr = [];
arr.push(1, 2);
console.log(arr); // 1,2
Object.defineProperty(obj, "name", {
  value: arr,
  enumerable: true,
});
console.log(obj.name); // 1,2
console.log(JSON.stringify(obj)); // {}

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Why does the property need to be enumerable?
@Sandi: Basically because the stringify method needs to enumerate the properties in order to find them and add them to the JSON result. I imagine they must have made this design decision in order to be able to easily exclude properties.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.