2

I have a JSON object with user information, its a large array of thousand of users an example of one is:

[ { 
    "FirstName" : "Joe",
    "LastName" : "Doe",
    "Address" : "123 Main Street"
   }
]

I want to be able to search in this json array based on first and last name and return the object that matches.

Pacman
  • 2,183
  • 6
  • 39
  • 70
  • Then iterate over that array and find that one that matches? Which problem do you have? – Jonas Wilms Dec 20 '17 at 18:40
  • Possible duplicate of [Find a value in an array of objects in Javascript](https://stackoverflow.com/questions/12462318/find-a-value-in-an-array-of-objects-in-javascript) – James Dec 20 '17 at 18:53

3 Answers3

5

Take a look at es6-feature

There're 2 method in array:

  • find: array.find(x => x.firstName === 'Joe' && x.LastName === 'Doe' ): returns single matche which means exactly 1 object or null.
  • filter: array.filter(x => x.firstName === 'Joe' && x.LastName === 'Doe' ) returns array of matches.
Rocard Fonji
  • 375
  • 3
  • 12
deathangel908
  • 8,601
  • 8
  • 47
  • 81
1

you can use the filter function on array

var result = largeJsonArray.filter(function(item){
   return item.FirstName === 'Jhon' && item.LastName === 'Doe'
});

result is a list of element that match the criteria

take a look to the documentation

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

stalin
  • 3,442
  • 2
  • 25
  • 25
  • var foundItem = userData.filter(user => { return user.FirstName === userParts[0] && user.LastName === userParts[1]; }); I am getting error 'filter is not a function' – Pacman Dec 20 '17 at 18:44
  • filter only exists on javascript arrays, check if userData is an array – stalin Dec 20 '17 at 20:32
1

You can parse json and use Array.prototype.find:

const arr = JSON.parse("your json")

const result = arr.find(elem => elem.FirstName === "Joe")
Sergo Pasoevi
  • 2,833
  • 3
  • 27
  • 41