Skip to content

Commit 52cdd18

Browse files
committed
make data merge recursive (followup in vuejs#594)
1 parent e2fba07 commit 52cdd18

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

src/util/merge-option.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,18 @@ var extend = _.extend
1616
var strats = Object.create(null)
1717

1818
/**
19-
* Helper that merges two data objects together
19+
* Helper that recursively merges two data objects together.
2020
*/
2121

2222
function mergeData (to, from) {
23-
for (var key in from) {
23+
var key, toVal, fromVal
24+
for (key in from) {
25+
toVal = to[key]
26+
fromVal = from[key]
2427
if (!to.hasOwnProperty(key)) {
25-
to.$add(key, from[key])
28+
to.$add(key, fromVal)
29+
} else if (_.isObject(toVal) && _.isObject(fromVal)) {
30+
mergeData(toVal, fromVal)
2631
}
2732
}
2833
return to

test/unit/specs/util/merge-option_spec.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -160,21 +160,25 @@ describe('Util - Option merging', function () {
160160

161161
it('class data merge', function () {
162162
function fn1 () {
163-
return { a: 1, c: 4 }
163+
return { a: 1, c: 4, d: { e: 1 } }
164164
}
165165
function fn2 () {
166-
return { a: 2, b: 3 }
166+
return { a: 2, b: 3, d: { f: 2 } }
167167
}
168168
// both present
169169
var res = merge({data:fn1}, {data:fn2}).data()
170170
expect(res.a).toBe(2)
171171
expect(res.b).toBe(3)
172172
expect(res.c).toBe(4)
173+
expect(res.d.e).toBe(1)
174+
expect(res.d.f).toBe(2)
173175
// only parent
174176
res = merge({data:fn1}, {}).data()
175177
expect(res.a).toBe(1)
176178
expect(res.b).toBeUndefined()
177179
expect(res.c).toBe(4)
180+
expect(res.d.e).toBe(1)
181+
expect(res.d.f).toBeUndefined()
178182
})
179183

180184
it('instanace el merge', function () {

0 commit comments

Comments
 (0)