Search code examples
javascriptjqueryarraysjsonparsing

Filter array based property value


I have a JSON file containing 13k objects. I need to get only the objects which have the events { name: "Submitted"} property from it. events is an array of objects which contain multiple name properties. Here is a screenshot of how it looks:

{
  "_id": "03c319a5-86d4-4ce6-ba19-1a50584cecb4",
  "_rev": "21-7cb67ebb46c485ff443995fc27bdd950",
  "doctype": "application",
  "events": [{
      "name": "change",
      "time": 1532547503182
    },
    {
      "name": "change",
      "time": 1532547503182
    },
    {
      "name": "submitted",
      "time": 1532547503182
    },
    {
      "name": "edited",
      "time": 1532547503182
    }
  ]
}

This is how I get all the object inside the json file:

$.getJSON("export.json", function(data) {
  var data = [];
  var arrays = data;

  var i;
  for (i = 0; i < arrays.length; i++) {
    console.log(arrays[i]);
  }
});

Now I need to push all the objects which have events[name:submitted] I get in arrays[i] into the doc[]. How can I filter the results?


Solution

  • You can use filter(), checking each element in the events array to see if the name is equal to submitted:

    const object = {
      "_id": "03c319a5-86d4-4ce6-ba19-1a50584cecb4",
      "_rev": "21-7cb67ebb46c485ff443995fc27bdd950",
      "doctype": "application",
      "events": [{
          "name": "change",
          "time": 1532547503182
        },
        {
          "name": "change",
          "time": 1532547503182
        },
        {
          "name": "submitted",
          "time": 1532547503182
        },
        {
          "name": "edited",
          "time": 1532547503182
        }
      ]
    }
    
    const filtered  = object.events.filter(obj => obj.name === 'submitted')
    console.log(filtered)