-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?

3
  • 2
    arr.findIndex(obj => obj[ref] === refVal)? Commented Dec 31, 2017 at 1:51
  • And Dynamically access object property using variable. Please don’t ask multiple questions per post. Commented Dec 31, 2017 at 1:53
  • This is better suited for the Code Review SE Commented Dec 31, 2017 at 2:17

2 Answers 2

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"));
Sign up to request clarification or add additional context in comments.

Comments

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"]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.