Searching through an object array in JavaScript to find a specific value and identify the property containing that value is my current task. Here's an example:
Object Array:
var objArray = [{
"ID": 1,
"Name": "Kathy",
"Position": "Programer",
"Hobbies": "Computers",
"Car": "Mustang"
},
{
"ID": 2,
"Name": "John",
"Position": "Programing",
"Hobbies": "Fishing",
"Car": "Ferrari"
},
{
"ID": 3,
"Name": "John",
"Position": "Sales",
"Hobbies": "Programing",
"Car": "Audi"
},
{
"ID": 4,
"Name": "William",
"Position": "Marketing",
"Hobbies": "Movies",
"Car": "Corvette"
},
{
"ID": 5,
"Name": "Stephanie",
"Position": "Director",
"Hobbies": "Jogging",
"Car": "Ferrari"
}
];
If I want to locate any values that contain Program
:
JavaScript:
function findMe(array, value) {
var results = [];
for (var i = 0; i < array.length; i++) {
if (String(Object.values(array[i])).indexOf(value) >= 0) {
results.push(array[i]);
}
}
return results;
}
var obj = findMe(objArray, 'Program');
The function successfully populates obj
with all entries containing the substring Program
.
However, I now face the challenge of determining which property within the array holds the identified value.
In this scenario: The properties Position
and Hobbies
both contain the value Program
.