This code gives me the index of a nested literal with a specified reference value
var arr = [
{ ref: "a", data:"foo" },
{ ref: "b", data:"bar" }
];
function getIndexOfObjectWithRef(arr, refVal) {
for (var i=0; i < arr.length; i++) {
if (arr[i].ref === refVal) return i;
};
}
console.log(getIndexOfObjectWithRef(arr, "b")); // 1
Two questions:
1) Is there a more efficient way to code this, either in terms of code cleanliness or in terms of performance?
2) Let's say I wanted to abstract this to allow the user to specify the key (ie: so that ref
was not hard-coded in. Is there a way to do this without using eval
?