0

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?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
loliki
  • 947
  • 2
  • 16
  • 38
  • 1
    Why not filter it from where it from (backend)? Im not sure if there is an impact if you loop thru 13k of objects. – Eddie May 29 '19 at 08:49
  • @Eddie this looks like PouchDB. Since it is a JS library that uses the IndexedDB it can‘t be really filtered at the backend. But there is a query function in PouchDB which you should take a look at as it is more efficient. – Aaron3219 May 29 '19 at 08:56

2 Answers2

2

You can filter your array of the object by filter method.

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

  var newArray = arrays.filter(function (el) {
    return el.name == 'Submitted';
  });

  console.log(newArray);
});

You can also do in one line using ES6 arrow function

var newArray  = arrays.filter(el => el.name === 'Submitted')
Paresh Barad
  • 1,544
  • 11
  • 18
1

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)
Kobe
  • 6,226
  • 1
  • 14
  • 35