Skip to content

Commit cab88d5

Browse files
committed
adding
1 parent 391949b commit cab88d5

File tree

3 files changed

+51
-6
lines changed

3 files changed

+51
-6
lines changed

src/index.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import Components from './components/index';
22
import Filters from './filters/index';
3-
import Util,{getTypes, addType, addValidationMessage, set} from './util';
3+
import Util,{getTypes, addType, addValidationMessage, set, get} from './util';
44
import Directives from './directives/index';
55

66

@@ -16,7 +16,8 @@ let Formly = {
1616
Filters(Vue);
1717

1818
Vue.$formly = {getTypes, addType, addValidationMessage};
19-
Vue.prototype.$formlySet = set
19+
Vue.prototype.$formlySet = set;
20+
Vue.prototype.$formlyGet = get;
2021
}
2122
};
2223

src/util.js

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,25 @@ export function set(target, key, val){
3838
}
3939
}
4040

41+
/**
42+
* returns an object value by string
43+
* https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key
44+
* @param {Object} target
45+
* @param {String} key
46+
*/
4147
export function get(target, key){
42-
if ( !key in target ){
43-
44-
} else {
45-
return target[key];
48+
key = key.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
49+
key = key.replace(/^\./, ''); // strip a leading dot
50+
var a = key.split('.');
51+
for (var i = 0, n = a.length; i < n; ++i) {
52+
var k = a[i];
53+
if (k in target) {
54+
target = target[k];
55+
} else {
56+
return;
57+
}
4658
}
59+
return target;
4760
}
4861

4962
/**

test/unit/specs/index.spec.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,37 @@ describe('module', () => {
7070
expect(output).to.be.false;
7171
});
7272

73+
describe('get()', () => {
74+
75+
it('should be present on the Vue instance', () => {
76+
const test = new Vue();
77+
expect(test.$formlyGet).to.be.a('function');
78+
});
79+
80+
it('should return nested fields', () => {
81+
const test = new Vue({
82+
data: {
83+
deeply: {
84+
nested: {
85+
child: 'foo',
86+
},
87+
arr: [
88+
{
89+
foo: 'bar'
90+
},
91+
{
92+
bar: 'foo'
93+
}
94+
]
95+
}
96+
}
97+
});
98+
expect(test.$formlyGet(test.deeply, 'nested.child')).to.equal('foo');
99+
expect(test.$formlyGet(test.deeply, 'arr[1].bar')).to.equal('foo');
100+
});
101+
102+
});
103+
73104
describe('set()', () => {
74105

75106
it('should be present on the Vue instance', () => {

0 commit comments

Comments
 (0)