Skip to content

Instantly share code, notes, and snippets.

@riston
Last active January 1, 2016 12:39
Show Gist options
  • Save riston/8145834 to your computer and use it in GitHub Desktop.
Save riston/8145834 to your computer and use it in GitHub Desktop.
Access the Javascript objects with namespace style 'person.name' ...
'use strict';
var expect = require('expect.js');
function get(object, namespace) {
var keys = namespace.split('.'),
currentObj = object,
current;
while (current = keys.shift()) {
if (current in currentObj) {
currentObj = currentObj[current];
} else {
return null;
}
}
return currentObj;
}
describe('Template spec', function() {
it('should get the object by key name', function () {
var obj = {
name: 'Mikk'
};
expect('Mikk').to.eql(get(obj, 'name'));
});
it('should get double nested object by name', function () {
var obj = {
person: {
name: 'Mikk'
}
};
expect({ name: 'Mikk' }).to.eql(get(obj, 'person'));
expect('Mikk').to.eql(get(obj, 'person.name'));
});
it('should have access to any level of object', function () {
var obj = {
person: {
name: 'Mikk',
age: 33,
property: {
car: 'BMW'
}
}
};
expect(33).to.eql(get(obj, 'person.age'));
expect('BMW').to.eql(get(obj, 'person.property.car'));
});
it('should also access first level objects', function () {
var obj = {
person: {
name: 'Mick',
children: [
'Licker',
'Liquid',
'John'
]
}
};
expect('Licker').to.eql(get(obj, 'person.children.0'));
expect('Liquid').to.eql(get(obj, 'person.children.1'));
expect('John').to.eql(get(obj, 'person.children.2'));
});
it('should be able to access array based objects', function () {
var obj = {
results: [
{
name: 'John',
age: 33
},
{
name: 'Jack',
age: 89
}
]
};
expect('John').to.eql(get(obj, 'results.0.name'));
expect(33).to.eql(get(obj, 'results.0.age'));
expect('Jack').to.eql(get(obj, 'results.1.name'));
expect(89).to.eql(get(obj, 'results.1.age'));
});
it('should return null if the result is not found', function () {
var obj = {
person: {
nicknames: [
'Jacker',
'Jackson'
]
}
};
expect(null).to.eql(get(obj, 'person.nicknames.notexisting'));
expect(null).to.eql(get(obj, 'person.nicknames.3'));
});
it('should change the object value after set new one', function () {
var obj = {
person: {
name: 'Jack'
}
};
var ref = get(obj, 'person');
expect({ name: 'Jack' }).to.eql(ref);
ref.name = "Maria";
expect({ name: 'Maria' }).to.eql(get(obj, 'person'));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment