I am not sure if I am describing this problem well in my subject. I am not sure that 'location' is the proper way of describing the location of a parameter that is deeply nested within an object.
The following is a function that I have created that searches an array of objects and returns the index of the first object that has a property of a particular value.
function indexOfItemWithParam( items, location, value ) {
var itemsIndex,
directions = location.split( '.' ),
directionsIndex,
property;
for( itemsIndex = 0; itemsIndex < items.length; itemsIndex++ ) {
property = items[ itemsIndex ];
for( directionsIndex = 0; directionsIndex < directions.length; directionsIndex++ ) {
property = property[ directions[ directionsIndex ] ];
}
if( property == value ) {
return itemsIndex;
}
}
return false;
}
The special thing about this function is that if you have objects containing objects containing objects etc. you can describe the location of a property deep within the object hierarchy.
var people = [
{
id: 1,
names: {
first: 'John',
last: 'Smith'
},
age: 45
},
{
id: 2,
names: {
first: 'Jane',
last: 'Jones'
},
age: 30
},
];
console.log( indexOfItemWithParam( people, 'names.first', 'Jane' ) );
The console will return index position 1
. The location of the first object with property names
with property first
of value Jane
. As you can see I am passing a string mimics the the way an object is navigated in JavaScript, split it into an array using the full stop as a delimiter and then loop through each item to navigate through the objects.
This feels weird and like there should be a better way of doing this. I have not been able to find any other examples of functions trying to do a similar thing. Is this method, i.e. pass string, explode and loop, the best way to navigate nested objects?