Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read-only JSON object in node.js

Tags:

json

node.js

I need to give users result as a JSON Object and I cache the result.

In some cases users change this result object and the modified version is available to successive users. To avoid this I'm currently cloning result but this leads to heavy overhead as its very large JSON object.

So I want to make JSON read only for giving result and avoid clone process. How to make a JSON Object non editable ?

like image 304
vashishatashu Avatar asked Nov 01 '22 14:11

vashishatashu


1 Answers

You can use Object.freeze() for that:

var obj = {a: 'a', b: 'b'};
var freezeObj = Object.freeze(obj);

freezeObj.a = 'c';

console.log("%j", freezeObj);   // prints {"a":"a","b":"b"}
console.log("%j", obj);         // prints {"a":"a","b":"b"}
console.log(obj === freezeObj); // prints true
like image 186
Ben Avatar answered Nov 13 '22 23:11

Ben