On ToJSON method of JS Object

Source: Internet
Author: User
Tags tojson

A few days ago in the "talking about Json.stringify method" said his correct use posture, today, the next ToJSON method.
In fact, I think the goods with the toString a reason, he is to give the Stringify method is called when the string.
Take a look at the official MDN document "ToJSON behavior".
It's very simple, but it's important to note that he and the Stringify method have a slightly different second argument.
Because the second parameter of stringify is the callback function, only the value corresponding to the current key is modified.
ToJSON, however, modifies the current object.
For example:

var obj = {    key: ' foo '};var ret = json.stringify (obj, function (k, v) {    return k = = = "Key"? V.touppercase (): v;} ); Console.log (ret); var obj = {    key: ' foo ',    tojson:function () {        return ' bar ';    }}; var ret = json.stringify (obj); Console.log (ret);

The difference is very obvious, ToJSON's return value directly replaces the current object, while the stringify callback function simply modifies the current value.

Of course they have their own uses, so look at the need to choose to use just fine.

Well, just share it today.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.