0

I know that I can search this array of objects by using a for loop and if statement,

var junkData = [
        { "ID": "1", "AreaName": "Area A Tester" },
        { "ID": "2", "AreaName": "Area B Test" },
        { "ID": "3", "AreaName": "Area C" },
        { "ID": "4", "AreaName": "Area D 12" },
        { "ID": "5", "AreaName": "Area E" }
];

but which other ways are available to me? I would like to search on the ID and then return that object. So if I wanted to search for ID 3, then it would return the object whose ID is 3.

What other options are available outside of using a for loop with an if statement?

Chris
  • 2,953
  • 10
  • 48
  • 118

2 Answers2

3

Use Array#find instead:

var junkData = [
        { "ID": "1", "AreaName": "Area A Tester" },
        { "ID": "2", "AreaName": "Area B Test" },
        { "ID": "3", "AreaName": "Area C" },
        { "ID": "4", "AreaName": "Area D 12" },
        { "ID": "5", "AreaName": "Area E" }
];

console.log(junkData.find(e => e.ID == 3))
BlackBeard
  • 10,246
  • 7
  • 52
  • 62
2

You can filter the results.

var junkData = [
  { "ID": "1", "AreaName": "Area A Tester" },
  { "ID": "2", "AreaName": "Area B Test" },
  { "ID": "3", "AreaName": "Area C" },
  { "ID": "4", "AreaName": "Area D 12" },
  { "ID": "5", "AreaName": "Area E" }
];

console.log(findBy(junkData, 'ID', '2', true));

function findBy(arr, key, val, onlyOne) {
  return (ret => onlyOne ? ret.shift() : ret)(arr.filter(item => item[key] === val));
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

The ret is the return of the filtered results (in the right parenthesis). I wrapped it in a self-returning function. You could also just assign the filtered results to a variable before returning.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132