Find by property
by chintsu
HTML
<div id="log"></div>
JavaScript
var log = function(message) {
var node = document.createElement('div');
var textnode = document.createTextNode(message);
node.appendChild(textnode);
document.getElementById('log').appendChild(node);
};
var findByProperty = function(obj, prop, value) {
var p, result = null;
if (typeof obj !== 'object') {
//log('typeof obj !== "object"');
return null;
}
//var keys = Object.keys(obj);
for (p in obj) {
if (obj.hasOwnProperty(p)) {
// break loop once we
if (result != null) {
log('result != null');
return result;
}
log('obj['+p+'] = ' + JSON.stringify(obj[p]));
if (obj[p] == null) {
return null;
}
// we found desired property with specified value
if (obj[p][prop] === value) {
log('obj[p][prop] === value');
return obj[p];
} else {
// keep looking
result = findByProperty(obj[p], prop, value);
//log('findByProperty(obj[p], prop, value)');
}
}
}
return result;
};
var obj1 = {
a1: 'goh',
b1: {
b21: 'val',
b22: 'val',
b23: 'val'
},
c1: {
c2: {
name: 'c2',
c3: 'val'
}
},
d1: {
name: 'd1',
c3: 'val'
},
e1: {
e2: {
e3: {
c3: 'val'
}
}
}
};
log('result: ' + JSON.stringify(findByProperty(obj1, 'c3', 'val')));