1

I have a JSONArray containing JSONObjects like this {firstname:'John', lastname:'Doe'}.

Is there a way to select all JSONObjects having firstname == 'John' directly or the only way is to loop the array, test the field firstname and save all matching objects in another array?

Thanks

Ionut
  • 1,729
  • 4
  • 23
  • 50

2 Answers2

2

You can filter them out:

var people = JSONArray.filter(function(obj) {
    return obj.firstname == "John";
});

FYI: You have an array containing objects.

tymeJV
  • 103,943
  • 14
  • 161
  • 157
2

The filter method should do the trick.

var jsonArrayString = '[{"firstname": "John","otherProp": "otherValue"},{"firstname": "other Name", "otherProp": "otherValue"}]';

var jsonArray = JSON.parse(jsonArrayString);

var filteredArray = jsonArray.filter(function(element) {
  return element.firstname === "John";
});

console.log(filteredArray);

Advice: The filter method is not supported in <= IE 8. but there is a polyfill in the MDN article.

Marvin
  • 539
  • 5
  • 17