Skip to content

Commit

Permalink
Merging array of objects
Browse files Browse the repository at this point in the history
  • Loading branch information
vvo committed Apr 3, 2012
1 parent e9633aa commit 9180a6d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
11 changes: 8 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,15 @@ module.exports = function merge (target, src) {
var dst = array && [] || {}

if (array) {
target = target || []
dst = dst.concat(target || [])
src.forEach(function(e, i){
if (!target || target.indexOf(e) === -1) {
dst.push(e);
src.forEach(function(e, i) {
if (typeof e === 'object') {
dst[i] = merge(target[i], e)
} else {
if (target.indexOf(e) === -1) {
dst.push(e);
}
}
})
} else {
Expand Down
19 changes: 18 additions & 1 deletion test/merge.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ test('should work on simple array', function (t) {
t.end()
})

test('should work on stored arrays', function (t) {
test('should work on array properties', function (t) {
var src = {key1 : ['one', 'three'], key2 : ['four']}
var target = {key1 : ['one', 'two']}

Expand All @@ -131,3 +131,20 @@ test('should work on stored arrays', function (t) {
t.ok(Array.isArray(merge(target, src).key2))
t.end()
})

test('should work on array of objects', function (t) {
var src = [{key1: ['one', 'three'], key2: ['one']}, {key3: ['five']}]
var target = [{key1: ['one', 'two']}, {key3 : ['four']}]

var expected = [{key1: ['one', 'two', 'three'], key2: ['one']}, {key3: ['four', 'five']}]

t.deepEqual(target, [{key1: ['one', 'two']}, {key3 : ['four']}])
t.deepEqual(merge(target, src), expected)
t.ok(Array.isArray(merge(target, src)), 'result should be an array')
t.ok(Array.isArray(merge(target, src)[0].key1), 'subkey should be an array too')

t.end()
})



0 comments on commit 9180a6d

Please sign in to comment.