-1

This has been causing me some issues solving:

If I have JSON object coming from a REST endpoint such as this;

SomeArray = 
[{"id":"1","genre":"Folk"},
{"id":"2","genre":"punk"},
{"id":"13","genre":"Punk (original)"},
{"id":"14","genre":"Punk (revival)"},
{"id":"25","genre":"Hard Rock"},
{"id":"66","genre":"Heavy Metal"} ..... ]

and I know that I want to access the item with an id of 25 for example, and get the value of genre

This for example:

 var myID = 25
 var my value = SomeArray[myID].genre

looks to the 25th element of the JSON object SomeArray. How can I properly access the sibling of the element with the id = 25 for example and return the genre value?

I tried

SomeArray.id[myID].genre but not correct syntax of course. 

Thanks for any help

This is in an angular controller if there is anything in angular that might assist also you might be aware of.

user2420225
  • 97
  • 2
  • 10
  • Possible duplicate of [Find object by id in array of javascript objects](http://stackoverflow.com/questions/7364150/find-object-by-id-in-array-of-javascript-objects) – skobaljic Dec 08 '15 at 03:31
  • You don't really want the 25th item, but the item with id = 25, correct? – CRice Dec 08 '15 at 03:31
  • yes , want the item with the id=25, but keep getting the index of the 25th item in the object – user2420225 Dec 08 '15 at 03:36

2 Answers2

1

I can't understand your question correctly but can't you user indexof function like below?

    var currentIndex = SomeArray.indexof(myId);
var siblin = SomeArray[currentIndex +1];
1

You could make a function loop through to find it:

function find(someArray, id){
 for (var i = 0; i < someArray.length; i++){
   if (someArray[i].id == id) {
    return someArray[i]; 
   }
  } 
  return null;
}

Then call it..

var item = find(someArray, 25);
var genre = item.genre;
CRice
  • 12,279
  • 7
  • 57
  • 84