Home > Software design >  Javascript JSON.stringify replacer return value problem?
Javascript JSON.stringify replacer return value problem?

Time:12-31

I tried to write some javascript code that multiplies with number salaries of each person, and makes them into string with JSON.stringify.

For example, in salaries, the name and the original salary are in here like this:

let salaries = {
        james:100000,
        john:200000,
        jane:300000
    };

and I want to express like this: {james:110000,john:220000,jane:330000}

So, I wrote the code like...

let payjson = JSON.stringify(pays, function replacer(key, value){
        return value*1.1;
    }); // 1st try

and got an error, the values are changed like [object Object], NaN.

However, this code just worked for me

let payjson = JSON.stringify(pays, function replacer(key, value){
        return Number.isInteger(value)? Math.floor(value*1.1): value;
    }); // 2nd try

I wonder why the first one didn't work the way I wanted and the second just worked the way I wanted to.

CodePudding user response:

As the stringify() function documentation clearly explain, the replacer function is initially passed the object, and then each of the properties. So, you are seeing this behavior. The first time when the value comes in as object type, and the multiplication is attempted, it crashes and does not subsequently pass the properties, so the overall return of the stringify() is null. In your 2nd try code, you are checking the value and only if it is of numeric type, you are doing the math and returning a calculated value, which is used by stringify() to append to the output string.

See the documentation, and mainly this paragraph :

Initially, the replacer function is called with an empty string as key representing the object being stringified. It is then called for each property on the object or array being stringified.

CodePudding user response:

It looks like you want to create a copy of the original object with 10% higher salaries:

const salaries = {
    james:100000,
    john:200000,
    jane:300000
};

const res=Object.fromEntries(Object.entries(salaries).map(([k,v])=>[k,1.1*v]));

console.log(res);
// this can be strigified too:
console.log(JSON.stringify(res));
// and the input object is unchanged:
console.log(salaries);

CodePudding user response:

When the replacer function is first called, key is assigned an empty string. However, the function is still expected to return value, otherwise it terminates.

let salaries = {
        james:100000,
        john:200000,
        jane:300000
    };
document.write(JSON.stringify(salaries,(k,v)=>{return k==''?v:Math.floor(v*1.1);}));

  • Related