-2

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?

drenl
  • 1,321
  • 4
  • 18
  • 32

2 Answers2

1

If the ref values are unique, they can be used as keys:

var data = { "a": "foo", "b": "bar" }

console.log( data["b"] )  // "bar"

If not, then similar lookup:

var data = { "a": ["foo"], "b": ["bar", "baz"] }

console.log( data["b"] )  // ["bar", "baz"]
Slai
  • 22,144
  • 5
  • 45
  • 53
1

there are many ways to do this. here is one

var arr = [
  { ref: "a", data:"foo" },
  { ref: "b", data:"bar" }
];

function indexOf(arr, key, val) {
  var index = -1;
  arr.some(function(item, idx) {
    if (arr[idx][key] === val) {
      index = idx;
      return true;
    }
    return false;
  });
  return index;
}

console.log(indexOf(arr, "ref", "b"));
D. Seah
  • 4,472
  • 1
  • 12
  • 20