diff --git a/src/object.js b/src/object.js index 393589d04..89fc01703 100644 --- a/src/object.js +++ b/src/object.js @@ -178,13 +178,17 @@ inherits(ObjectSchema, MixedSchema, { from(from, to, alias) { return this.transform( obj => { - if ( obj == null) + var newObj = obj; + + if (obj == null) return obj - var newObj = transform(obj, (o, val, key) => key !== from && (o[key] = val), {}) + if (has(obj, from)) { + newObj = transform(obj, (o, val, key) => key !== from && (o[key] = val), {}) + newObj[to] = obj[from] - newObj[to] = obj[from] - if(alias) newObj[from] = obj[from] + if(alias) newObj[from] = obj[from] + } return newObj }) @@ -248,4 +252,4 @@ function sortFields(fields, excludes = []){ } return toposort.array(nodes, edges).reverse() -} \ No newline at end of file +} diff --git a/test/object.js b/test/object.js index b42abf266..cda828b45 100644 --- a/test/object.js +++ b/test/object.js @@ -291,6 +291,19 @@ describe('Object types', function(){ .should.eql({ myProp: 5, other: 6, Other: 6 }) }) + it('should not move keys when it does not exist', function(){ + var inst = object().shape({ + myProp: mixed(), + }) + .from('prop', 'myProp') + + inst.cast({ myProp: 5 }) + .should.eql({ myProp: 5 }) + + inst.cast({ myProp: 5, prop: 7 }) + .should.eql({ myProp: 7 }) + }) + it('should handle conditionals', function(){ var inst = object().shape({ noteDate: number() @@ -415,4 +428,4 @@ describe('Object types', function(){ }) -}) \ No newline at end of file +})