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?

2
  • 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. Commented May 29, 2019 at 8: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. Commented May 29, 2019 at 8:56

2 Answers 2

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')
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.