Home > database >  Why are the two results different in JSON.stringify?
Why are the two results different in JSON.stringify?

Time:10-27

I expected JSON.stringify(all) === JSON.stringify(updatedAll2) to be false, but it is true. And I don't understand the result of this. Can you explain why it comes out like this?

Here's my code:

const all = {
  name: "oneny",
  schools: [{
      name: "Yorktown",
      students: 100
    },
    {
      name: "Stratford",
      students: 120
    },
    {
      name: "Washington & Lee",
      students: 200
    },
    {
      name: "Wakefield",
      students: 300
    },
  ],
};

const updatedAll = {
  ...all,
  schools: all.schools.map((e, i) => {
    return e.name === "Stratford" ? { ...e,
      students: 119
    } : e;
  }),
}

const updatedAll2 = {
  ...all,
  schools: all.schools.map((e, i) => {
    return e.name === "Stratford" ? { ...e,
      students: --e.students
    } : e;
  }),
}

console.log(JSON.stringify(all) === JSON.stringify(updatedAll));
console.log(JSON.stringify(all) === JSON.stringify(updatedAll2));

CodePudding user response:

When you use Array.prototype.map(), if the element passed to your callback is an object, then mutating it will also mutate the original object in the original array. To see this in action, try printing all after the .map() call. You will see that it has been changed.

const all = {
  name: "oneny",
  schools: [{
      name: "Yorktown",
      students: 100
    },
    {
      name: "Stratford",
      students: 120
    },
    {
      name: "Washington & Lee",
      students: 200
    },
    {
      name: "Wakefield",
      students: 300
    },
  ],
};

const updatedAll = {
  ...all,
  schools: all.schools.map((e, i) => {
    return e.name === "Stratford" ? { ...e,
      students: 119
    } : e;
  }),
}

const updatedAll2 = {
  ...all,
  schools: all.schools.map((e, i) => {
    return e.name === "Stratford" ? { ...e,
      students: --e.students
    } : e;
  }),
}

// Print all, which has been mutated
console.log(all)

console.log(JSON.stringify(all) === JSON.stringify(updatedAll));
console.log(JSON.stringify(all) === JSON.stringify(updatedAll2));

  • Related