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.

3
  • RTM Commented Jun 24, 2020 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. Commented Jun 24, 2020 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. Commented Jun 24, 2020 at 20:31

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

MEGA Dupe!!!!!!
I'm assuming this is just an O(n) function to find this item similar to looping?
-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));

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.