A very simple function for looking up a value in an object using a keypath string.
Often useful when working with large objects such as JSON data returned from a server as it allows quick navigation to only the required information.
object - An Object to query.
path - A dot sepeated keypath eg. 'artist.album.name'
fallback - An optional fallback value to return.
prototype - Boolean, if true keypath will traverse the prototype chain.
Returns the queried keypath if found. Otherwise returns null
unless a
fallback parameter is provided.
var data = {
tracks: [
{
name: 'Michelle',
url: 'http://www.last.fm/music/The+Beatles/Rubber+Soul/Michelle',
album: {
name: 'Rubber Soul'
url: 'http://www.last.fm/music/The+Beatles/Rubber+Soul'
tracks: 12
},
artist: {
name: 'The Beatles',
url: 'http://www.last.fm/music/The+Beatles'
}
}
]};
keypath(data, 'tracks.0.artist.name');
//=> 'The Beatles'
keypath(data, 'tracks.0.duration');
//=> null
keypath(data, 'tracks.0.duration', '2.42');
//=> '2.42'
To use with node.js:
var keypath = require('keypath');
keypath(data, 'tracks.0.duration');
To use with AMD loader (such as curl.js or require.js):
require(['keypath'], function (keypath) {
var keypath = require('keypath');
keypath(data, 'tracks.0.duration');
});
Public: Restores the previous "keypath" property on the current scope and returns the function. Use this to redefine the function in a different namespace, for example to add the function as a jQuery plugin.
Returns the keypath()
Function.
jQuery.keypath = keypath.noConflict();
jQuery.keypath(data, 'tracks.0.duration');
Released under the MIT license