QuepasaTio QuepasaTio - 2 months ago 9
Javascript Question

Javascript How to search in array by field

I have a variable which holds this data:

{"main":[
{"id":"123","name":"name 1"},
{"id":"234","name":"name 2"}

]
}


I know the id of the data I want to search.

My question is...How do I search for the name of id 234 (for example) is thw data above?

Answer

Use Array#filter

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

var object = {
  "main": [{
    "id": "123",
    "name": "name 1"
  }, {
    "id": "234",
    "name": "name 2"
  }]
};
var toFind = "234";
var filtered = object.main.filter(function(el) {
  return el.id === toFind;
});
console.log(filtered);

If there is only one object in the array, for-loop with break could be preferred.

var object = {
  "main": [{
    "id": "123",
    "name": "name 1"
  }, {
    "id": "234",
    "name": "name 2"
  }]
};
var toFind = "234";
for (var i = 0, len = object.main.length; i < len; i++) {
  if (object.main[i].id === toFind) {
    break;
  }
}
console.log(object.main[i].name);

Comments