I have a function that finds a property in a nested object by its name and returns its value. The function I got from another question on this site and so far it has been working great. I looks like this:
var _getPropertyValue = function (obj, field) {
// Create a result
var result = null;
// If our object is an array
if (obj instanceof Array) {
// For each array item
for (var i = 0; i < obj.length; i++) {
// Invoke our function for the current object
result = _getPropertyValue(obj[i], field);
// If we have a result
if (result) {
// Exit the loop
break;
}
}
// If we are an object
} else {
// For each property in our object
for (var prop in obj) {
// If our property matches our value
if (prop == field) {
// Return our value
return obj[prop];
}
// If our property is an object or an array
if (obj[prop] instanceof Object || obj[prop] instanceof Array) {
// Invoke our function for the current object
result = _getPropertyValue(obj[prop], field);
// If we have a result
if (result) {
// Exit the loop
break;
}
}
}
}
// Return our result
return result;
};
Now, I have thought that perhaps if I have an object like this:
{
name: 'test',
mode: 'default',
settings: {
mode: 'auto'
}
}
With my function, I believe that it will find the first mode and then exit the function. What I would prefer to do is specify the field parameter like this:
settings.mode
and for it to go straight to that place in my object and return the value. Does anyone know if that can be done?
Dispite this being closed. I answered this myself like this:
// Private function to get the value of the property
var _getPropertyValue = function (object, notation) {
// Get all the properties
var properties = notation.split('.');
// If we only have one property
if (properties.length === 1) {
// Return our value
return object[properties];
}
// Loop through our properties
for (var property in object) {
// Make sure we are a property
if (object.hasOwnProperty(property)) {
// If we our property name is the same as our first property
if (property === properties[0]) {
// Remove the first item from our properties
properties.splice(0, 1);
// Create our new dot notation
var dotNotation = properties.join('.');
// Find the value of the new dot notation
return _getPropertyValue(object[property], dotNotation);
}
}
}
};
I have further made this better like this:
// Private function to get the value of the property
var _getPropertyValue = function (obj, notation) {
// Get our properties
var properties = notation.split('.');
// Use reduce to get the value of the property
return properties.reduce(function (a, b) {
// Return our value
return a[b];
}, obj);
};