Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
node-getobject/lib/getobject.js /
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
60 lines (49 sloc)
1.46 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * getobject | |
| * https://github.com/cowboy/node-getobject | |
| * | |
| * Copyright (c) 2013 "Cowboy" Ben Alman | |
| * Licensed under the MIT license. | |
| */ | |
| 'use strict'; | |
| var getobject = module.exports = {}; | |
| // Split strings on dot, but only if dot isn't preceded by a backslash. Since | |
| // JavaScript doesn't support lookbehinds, use a placeholder for "\.", split | |
| // on dot, then replace the placeholder character with a dot. | |
| function getParts(str) { | |
| return str.replace(/\\\./g, '\uffff').split('.').map(function(s) { | |
| return s.replace(/\uffff/g, '.'); | |
| }); | |
| } | |
| // Get the value of a deeply-nested property exist in an object. | |
| getobject.get = function(obj, parts, create) { | |
| if (typeof parts === 'string') { | |
| parts = getParts(parts); | |
| } | |
| var part; | |
| while (typeof obj === 'object' && obj && parts.length) { | |
| part = parts.shift(); | |
| if (!(part in obj) && create) { | |
| obj[part] = {}; | |
| } | |
| obj = obj[part]; | |
| } | |
| return obj; | |
| }; | |
| // Set a deeply-nested property in an object, creating intermediary objects | |
| // as we go. | |
| getobject.set = function(obj, parts, value) { | |
| parts = getParts(parts); | |
| var prop = parts.pop(); | |
| obj = getobject.get(obj, parts, true); | |
| if (obj && typeof obj === 'object') { | |
| return (obj[prop] = value); | |
| } | |
| }; | |
| // Does a deeply-nested property exist in an object? | |
| getobject.exists = function(obj, parts) { | |
| parts = getParts(parts); | |
| var prop = parts.pop(); | |
| obj = getobject.get(obj, parts); | |
| return typeof obj === 'object' && obj && prop in obj; | |
| }; |