Skip to content

Instantly share code, notes, and snippets.

@MaraScott
Last active December 16, 2015 20:39
Show Gist options
  • Select an option

  • Save MaraScott/5494380 to your computer and use it in GitHub Desktop.

Select an option

Save MaraScott/5494380 to your computer and use it in GitHub Desktop.
Name : _getInfoOf() - Language : JavaScript - type : function - Platform : generic - tag : indexOf, object
// Extend an object to get the value of the first occurence of a specific index
var _getInfoOf = function (obj, index, path, isIndexExists) {
"use strict";
var prevPath = '';
if (typeof path !== 'undefined') {
prevPath = path + '.';
} // END IF
if (typeof isIndexExists === 'undefined') {
isIndexExists = [];
} // END IF
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (key !== index && typeof (obj[key]) === 'object') {
isIndexExists = _getInfoOf(obj[key], index, prevPath + key, isIndexExists);
} else if (key === index) {
isIndexExists[isIndexExists.length] = {
'path': prevPath + key,
'value': obj[key]
};
} // END IF
} // END IF
} // END FOR
return isIndexExists;
};
function multiIndex(obj,is) { // obj,[1,2,3] -> obj[1][2][3]
return is.length ? multiIndex(obj[is[0]],is.slice(1)) : obj
}
function pathIndex(is) { // obj,'1.2.3' -> obj[1][2][3]
return multiIndex(obj,is.split('.'))
}
var aObj={'jack':3, 'peter':4, '5':'col', 'kk':{'aa':22,'zz':0}, 'till':'ding'};
pathIndex(aObj,_getInfoOf(aObj,"aa")[0].path) = 1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment