9

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?

4 Answers4

10

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);
Rayon
  • 36,219
  • 4
  • 49
  • 76
2

In ES5 environment, you could use Array#some, if you expect only one result.

var data = { "main": [{ "id": "123", "name": "name 1" }, { "id": "234", "name": "name 2" }] },
    result;

data.main.some(function (a) {
    if (a.id === '234') {
        result = a;
        return true;
    }
});

console.log(result);

When you expect more than one result set, you may better use Array#filter

var data = { "main": [{ "id": "123", "name": "name 1" }, { "id": "234", "name": "name 2a" }, { "id": "234", "name": "name 2" }] },
    result = data.main.filter(function (a) {
        return a.id === '234';
    });

console.log(result);

In ES6 environment, you could use Array#find for the first found element, but if there are more to find, then use Array#filter.

var data = { "main": [{ "id": "123", "name": "name 1" }, { "id": "234", "name": "name 2" }] },
    result = data.main.find(a => a.id === '234');

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You can use find() if id's are unique.

var data = {"main":[
  {"id":"123","name":"name 1"},
  {"id":"234","name":"name 2"}
  ]
}

var name = data.main.find(function(o) {
  return o.id == '234';
}).name;

console.log(name)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0

You can use Array.prototype.filter to find all matching elements and return them as a new array.

To find just the first match, you can use Array.prototype.find (ES2015+).

mdziekon
  • 3,531
  • 3
  • 22
  • 32