让我们下一个
javascript对象.现在我想克隆它,但没有一些领域.例如我想要克隆对象没有字段“lastName”和“cars.age”
输入
输入
{ "firstName":"Fred","lastName":"McDonald","cars":[ { "type":"mersedes","age":5 },{ "model":"bmw","age":10 } ] }
输出(克隆)
{ "firstName":"Fred","cars":[ { "model":"mersedes" },{ "model":"bmw" } ] }
我可以做一些类似的事情
var human = myJson var clone = $.extend(true,{},human) delete clone.lastName _.each(clone.cars,function(car)) { delete car.age }
你知道更容易的解决方案吗?
解决方法
如果您不介意添加对象原型,这是一个简单的解决方案.您可能需要修改一些以供自己使用.
Object.prototype.deepOmit = function(blackList) { if (!_.isArray(blackList)) { throw new Error("deepOmit(): argument must be an Array"); } var copy = _.omit(this,blackList); _.each(blackList,function(arg) { if (_.contains(arg,'.')) { var key = _.first(arg.split('.')); var last = arg.split('.').slice(1); copy[key] = copy[key].deepOmit(last); } }); return copy; }; Array.prototype.deepOmit = function(blackList) { if (!_.isArray(blackList)) { throw new Error("deepOmit(): argument must be an Array"); } return _.map(this,function(item) { return item.deepOmit(blackList); }); };
那么当你有一个对象,如:
var personThatOwnsCars = { "firstName":"Fred","age":10 } ] };
你可以这样做魔术.
personThatOwnsCars.deepOmit(["firstName","cars.age"]);
甚至这样的魔法!
[person1,person2].deepOmit(["firstName","cars.age"]);