diff --git a/lib/utils/JSONBuilder.js b/lib/utils/JSONBuilder.js index 2ed15ec..5020baa 100644 --- a/lib/utils/JSONBuilder.js +++ b/lib/utils/JSONBuilder.js @@ -91,6 +91,33 @@ export default class JSONBuilder { return this; } + /** + * Will append the _value_ object to the building object by recursively calling toJSONObject() + * on each child if an object. + * + * @param name {String} The name to use as key. + * @param value {Array} The `Object` to append + */ + appendObject(name, value) { + let key, obj = {}; + + Utils.assertRequiredParameterIsObject(value, 'value'); + + for (key in value) { + if (value.hasOwnProperty(key)) { + if (typeof value[key] === 'object' && value[key].toJSONObject) { + obj[key] = value[key].toJSONObject(); + } else { + obj[key] = value[key]; + } + } + } + + this.append(name, obj); + + return this; + } + /** * @return an object with all appended values **/ diff --git a/test/common/utils/JSONBuilder.js b/test/common/utils/JSONBuilder.js index bf2b54f..90926d1 100644 --- a/test/common/utils/JSONBuilder.js +++ b/test/common/utils/JSONBuilder.js @@ -145,4 +145,37 @@ describe('The JSONBuilder class', function() { }); + describe('The appendObject method', function() { + + var obj = { one: 1, two: 2 }; + var Child = function(val) { + this.prop = val; + this.toJSONObject = function() { + return { value: this.prop }; + }; + }; + var complex = { foo: 'foo', child: new Child('bar') }; + + it('should throw an Error if the name is undefined', function() { + expect(function() { + new jmap.JSONBuilder().appendObject(undefined, {}); + }).to.throw(Error); + }); + + it('should throw an Error if date is not an Object', function() { + expect(function() { + new jmap.JSONBuilder().appendObject('obj', []); + }).to.throw(Error); + }); + + it('should append a clone of the object value', function() { + expect(new jmap.JSONBuilder().appendObject('obj', obj).build()).to.deep.equal({ obj: obj }); + }); + + it('should call toJSONObject() on object elements', function() { + expect(new jmap.JSONBuilder().appendObject('obj', complex).build()).to.deep.equal({ obj: { foo: 'foo', child: { value: 'bar' } } }); + }); + + }); + });