-1

I have a JSON feed (people.json) which spits out the following:

[  
   {  
      "id":0,
      "firstName":"Alison",
   },
   {  
      "id":1,
      "firstName":"Fred",
   }
]

etc.

EDIT for clarity**

I have a var called searchTerm. In JavaScript how can I find all records in this array where firstName matches searchTerm?

Matt Saunders
  • 4,073
  • 7
  • 33
  • 47

3 Answers3

0

it depends what exactly "search" is, if search is a person entity, or if search is the person id..

look at this Array.filter

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

function readJsonFile(path)
{
    var file = new XMLHttpRequest();
    file.open("GET", path, false);
    file.onreadystatechange = function (){
        if(file.readyState === 4){
            if(file.status === 200 || file.status == 0){

               var mydata =  JSON.parse(file.responseText);
               var result = mydata.filter(function (entry) {
                   return entry.firstname == searchTerm;
                   });
            }
        }
    }
    file.send(null);
}

now you should execute that function with your local file path.

readJsonFile("./people.json");

if the read from file code confusing - let me know and I'll build it better.

result will be an array of 'persons' with the value of searchTerm as their firstName.

Sahar Ben-Shushan
  • 297
  • 1
  • 3
  • 20
0

If you are looking for an object that matches firstName

var json = [  
   {  
      "id":0,
      "firstName":"Alison",
   },
   {  
      "id":1,
      "firstName":"Fred",
   }
];
function findByName(name) {
    return json.find( function(f) { return f.firstName == name});
}
console.log( findByName('Fred') );
Jarek Kulikowski
  • 1,399
  • 8
  • 9
0

You can find all objects that match your search term by using the filter function:

var searchTerm = "Alison";
var alisons = arr.filter(x => {
    return x.firstName === searchTerm;
});

Filter takes a callback funciton to filter out items, and only include items in the new array that fit the given criteria. If you're not familiar with ES6 syntax, this is just:

var searchTerm = "Alison";
var alisons = arr.filter(function(x){
    return x.firstName === searchTerm;
});

The returned variable, alisons, will be an array of all objects in your array whose first name was Alison.

In case you're curious, the filter function knows about searchTerm because of variable hoisting. Thought I'd mention that just in case you need to move things around for your own code: https://www.w3schools.com/js/js_hoisting.asp

Hope this helps!

Adam
  • 877
  • 2
  • 10
  • 24