Skip to content

Commit 163f435

Browse files
author
Evan You
committed
fix #251 get/set for keypaths with brackets
1 parent d4315d8 commit 163f435

File tree

2 files changed

+35
-7
lines changed

2 files changed

+35
-7
lines changed

src/utils.js

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1-
var config = require('./config'),
2-
toString = ({}).toString,
3-
win = window,
4-
console = win.console,
5-
def = Object.defineProperty,
6-
OBJECT = 'object',
7-
THIS_RE = /[^\w]this[^\w]/,
1+
var config = require('./config'),
2+
toString = ({}).toString,
3+
win = window,
4+
console = win.console,
5+
def = Object.defineProperty,
6+
OBJECT = 'object',
7+
THIS_RE = /[^\w]this[^\w]/,
8+
BRACKET_RE_S = /\['([^']+)'\]/g,
9+
BRACKET_RE_D = /\["([^"]+)"\]/g,
810
hasClassList = 'classList' in document.documentElement,
911
ViewModel // late def
1012

@@ -13,6 +15,16 @@ var defer =
1315
win.webkitRequestAnimationFrame ||
1416
win.setTimeout
1517

18+
/**
19+
* Normalize keypath with possible brackets into dot notations
20+
*/
21+
function normalizeKeypath (key) {
22+
return key.indexOf('[') < 0
23+
? key
24+
: key.replace(BRACKET_RE_S, '.$1')
25+
.replace(BRACKET_RE_D, '.$1')
26+
}
27+
1628
var utils = module.exports = {
1729

1830
/**
@@ -25,6 +37,7 @@ var utils = module.exports = {
2537
*/
2638
get: function (obj, key) {
2739
/* jshint eqeqeq: false */
40+
key = normalizeKeypath(key)
2841
if (key.indexOf('.') < 0) {
2942
return obj[key]
3043
}
@@ -41,6 +54,7 @@ var utils = module.exports = {
4154
*/
4255
set: function (obj, key, val) {
4356
/* jshint eqeqeq: false */
57+
key = normalizeKeypath(key)
4458
if (key.indexOf('.') < 0) {
4559
obj[key] = val
4660
return

test/unit/specs/utils.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,12 @@ describe('Utils', function () {
1717
assert.strictEqual(utils.get(obj, 'a.b.c'), 123)
1818
})
1919

20+
it('should work on keypath with brackets', function () {
21+
var obj = { a: { 'key-with-dash': { b: 123 } }}
22+
assert.strictEqual(utils.get(obj, 'a["key-with-dash"].b'), 123)
23+
assert.strictEqual(utils.get(obj, "a['key-with-dash'].b"), 123)
24+
})
25+
2026
it('should return undefined if path does not exist', function () {
2127
var obj = { a: {}}
2228
assert.strictEqual(utils.get(obj, 'a.b.c'), undefined)
@@ -32,6 +38,14 @@ describe('Utils', function () {
3238
assert.strictEqual(obj.a.b.c, 123)
3339
})
3440

41+
it('should work on keypath with brackets', function () {
42+
var obj = { a: { 'key-with-dash': { b: 1 }}}
43+
utils.set(obj, 'a["key-with-dash"].b', 2)
44+
assert.strictEqual(obj.a['key-with-dash'].b, 2)
45+
utils.set(obj, "a['key-with-dash'].b", 3)
46+
assert.strictEqual(obj.a['key-with-dash'].b, 3)
47+
})
48+
3549
it('should set even if path does not exist', function () {
3650
var obj = {}
3751
utils.set(obj, 'a.b.c', 123)

0 commit comments

Comments
 (0)