0

Quick question, I want to return the object with id: 123from the current array of objects:

[
  {
    name: nancy,
    id: 999
  },
  {
    name: kim,
    id: 123
  },
  {
    name: tess,
    id: 888
  }
]

Any id how to do that?

Erik van de Ven
  • 4,747
  • 6
  • 38
  • 80
  • @OddDev No, it's not a duplicate of that, because he wants to find an element based on a property within the object. – Barmar Mar 27 '15 at 10:47
  • Indeed, NOT a duplicate. Just a side note: this object is invalid, you're missing some commas after each name. – briosheje Mar 27 '15 at 10:48
  • Excuse me, it's just an example. The actually array is much bigger so... But I tried array.contains(obj), but it returns false, which is not right.... – Erik van de Ven Mar 27 '15 at 10:51
  • Might there be more elements with the same id? I think this might be enough. http://jsfiddle.net/7zsy4g7j/ – briosheje Mar 27 '15 at 10:52
  • It seems like this is a duplicated question, as Barmar pointed out: http://stackoverflow.com/questions/7364150/find-object-by-id-in-array-of-javascript-objects. But I'm glad Krysztof posted a solution without using jQuery :) We are using Underscore for the main part, so.. – Erik van de Ven Mar 27 '15 at 13:18

2 Answers2

0

var list = [{
  name: 'nancy',
  id: 999
}, {
  name: 'kim',
  id: 123
}, {
  name: 'tess',
  id: 888
}]

function findById(list, id) {
  var index = list.map(function(element) {
    return element.id
  }).indexOf(id)
  return list[index]
}

document.getElementById('result').innerHTML = JSON.stringify(findById(list, 123))
<pre>
  <p>result: <code id="result"></code>
</pre>
Krzysztof Safjanowski
  • 7,292
  • 3
  • 35
  • 47
0

You can do it like this:

var array = [{
  name: "nancy",
  id: 999
}, {
  name: "kim",
  id: 123
}, {
  name: "tess",
  id: 888
}];

function getObjectById(id) {
  for (var i = 0; i < array.length; i++) {
    if(array[i].id === id){
      return array[i];
    }
  }
};

alert(getObjectById(123));
OddDev
  • 3,644
  • 5
  • 30
  • 53