To retrieve the names of properties from an object, you can utilize Object.keys and then employ indexOf to look for a specific value. However, keep in mind that indexOf only performs an exact match and does not accept regular expressions as an argument.
As a workaround, you may need to iterate through all the property names until you identify the desired one. Fortunately, there are built-in iterators that can assist in this process:
var exampleObject = {"status":200,
"success":true,
"result": [ {"Description":"desc",
"Year":"yr",
"Price/STK":"price/stk",
"Main Cat":"Fruits"}
]
};
function findValueLike(obj, property){
var regex = new RegExp('^' + property);
var targetValue;
Object.keys(obj).some(function(prop) {
if (regex.test(prop)) {
targetValue = obj[prop];
return true;
}
});
return targetValue;
}
document.write(findValueLike(exampleObject.result[0], 'Price')); // price/stk
Another approach that utilizes indexOf on the property name may offer improved speed and requires less code:
function findValueLike(obj, property){
var targetValue;
Object.keys(obj).some(function(key) {
if (key.indexOf(property) == 0) {
targetValue = obj[key];
return true;
}
});
return targetValue;
}
This can be further simplified to:
function findValueLike(obj, property, value){
Object.keys(obj).some(function(key) {return key.indexOf(property) == 0 && ((value = obj[key]) || true)});
return value;
}
While this last implementation allows for a default value to be specified for value, it may appear overly complex to some users.
Alternatively, you can utilize an arrow function:
function findValueLike(obj, property, value){
Object.keys(obj).some(key => key.indexOf(property) == 0 && ((value = obj[key]) || true));
return value;
}