0

I have a very complex object that looks like this:

    [
       {type: "type", data: {a ton more stuff}}, 
       //with tons of these objects.
    ] 

What I am wondering is if all 'type' keys are unique, could I get the object within the array with the given type or will I need to loop through the json array every time?? What I really need is the data, but I only know the type. This is a database schema that is not mine so unfortunately I cannot change the object.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Devon F
  • 63
  • 1
  • 7
  • [RTM](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) – mplungjan Jun 24 '20 at 20:23
  • "could I get the object within the array with the given type or will I need to loop through the json array every time??" yes, you will have to loop through the array. There are functions that can help you write this loop fairly quickly. – Code-Apprentice Jun 24 '20 at 20:30
  • If you are searching like this frequently, then you should just loop over the array once and create an object or a Map that will allow you to do the lookup more efficiently. – Code-Apprentice Jun 24 '20 at 20:31

2 Answers2

0

There may be a more efficient way, but you could use Array.prototype.find():

const item = items.find(i => i.type === 'yourType');

You could also loop through once and create a Map if type is unique, using type as the key and the object as the value. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

Anthony
  • 6,422
  • 2
  • 17
  • 34
-3

Short answer is yes. Since it is an array of objects you need to loop through it. What you need is

const newArr = oldArr.filter(obj => (obj.type && obj.type === 'myType' && obj.data) ? obj.data : false));
Helmer Barcos
  • 1,898
  • 12
  • 18
  • I don't understand why my answer gets downvotes. all Array functions like map, find, filter and others just loop though the array. Downvote an answer without any comment is also a bad practice. – Helmer Barcos Jun 24 '20 at 20:36