javascript - Making a copy of JS object an changing the occurrence of a given key -
i have few js objects. can have structure:
{ name: "first", _ref_id: 1234, spec: { _ref_id: 2345, data: "lots of data" } } { name: 'second', _ref_id: 5678, container: { _ref_id: 6789, children: [ {_ref_id: 3214, name: 'bob'} {_ref_id: 1111, name: 'mark'} {_ref_id: 2222, name: 'frank'} ] } }
problem:
i need make copies of object different _ref_ids.
creation of 'first' object this:
first = { name: "first", _ref_id: uuid.v4(), spec: { _ref_id: uuid.v4(), data: "lots of data" } }
so know structure of object when creating further down chain in place trying make copy of object don't have access , don't know structure of object have object self. after coping 'first' have:
{ name: "first", _ref_id: 8888, spec: { _ref_id: 9999, data: "lots of data" } }
i tried instead of defining _ref_id simple value sort of memoized function during object creation:
refid(memoized = true){ var memo = {} return () => { if(!memoized) memo = {} if(memo['_ref_id']) return memo._ref_id else { memo._ref_id = uuid.v4() return memo._ref_id } } }
so can create it:
first = { name: "first", _ref_id: refid(), spec: { _ref_id: refid(), data: "lots of data" } }
and change first._ref_id first._ref_id() whenever trying access value of it.
but have no idea how reset memoized variable inside coping function or if possible?
have had similar problem? maybe there different way solve it?
ps:
i using lodash , immutable.js in project haven't found helper functions particular task.
inspired most elegant way clone js object, check _ref_id
fields :
function deepcopywithnewrefid(obj) { if (null == obj || "object" != typeof obj) return obj; var copy = obj.constructor(); (var attr in obj) { if (obj.hasownproperty(attr)) { if (attr == "_ref_id") { copy[attr] = uuid.v4(); } else { copy[attr] = deepcopywithnewrefid(obj[attr]); } } } return copy; }
a log of use :
var uuid = { v4 : function(){ return math.random()} }; var first = { name: "first", _ref_id: uuid.v4(), spec: { _ref_id: uuid.v4(), data: "lots of data" } }; console.log(first._ref_id); console.log(first.spec._ref_id); var second = deepcopywithnewrefid(first); console.log(second); console.log(second._ref_id); console.log(second.spec._ref_id); // printed values not same. rest of object
Comments
Post a Comment