0

I have an JavaScript object which is being pushed to a global object.

var storedElement = {
    element: currentElement, 
    parentElement: parentElement,
    elementChild: currentChild
}

storedElement is being pushed to a global array called. pastLocations = []

I'm essentially trying to keep a history of the locations an element has been to. To do this I'm wanting to store these properties into the global array. If the same element already exists and has the same parent in the global then I dont want to push, but if the parent is different then push.

Is there a way I can put a unique key with item so I quickly and effectively get access to this element in the object. At the moment I currently have several for each loops to get the data from the object but this inst a practical approach. As Ideally I want 1 function to push to the global and to retrieve an element.

If I was to provide a unique keys for each object, how would I would know what key it is based of just knowing the element ?

2
  • you could use a map with element and parentElement as key, and the object as value. no need for another unique key. Commented Sep 13, 2016 at 8:39
  • Thanks for your answer will look into the map Commented Sep 13, 2016 at 8:44

1 Answer 1

1

In Javascript, an array [...] stores sequential values, preserving their order, and provides fast access if you know the index.

An object or dictionary {...} stores values along with a key, without preserving their order, and provides fast access if you know the key.

If you only need to store elements with distinct 'parent', you can use an object, using the parent as key. If you also need to browse them in order, your best bet is to use both an array and an object:

storedElements = []
storedByParent = {}

What you store in each depends on your application requirements. You may store a copy of the object:

newEl = {element: ..., parent: parentElement, ...}
storedElements.push(newEl)
storedByParent[parentElement] = newEl

Or you may store an index into the array:

storedElements.push(newEl)
storedByParent[parentElement] = storedElements.length - 1

Or you may store a simple boolean value, to just keep track of which parents you have seen:

storedElements.push(newEl)
storedByParent[parentElement] = true

This latter use of an object is usually known as 'set', because it's similar to the mathematical object: even if you call mySet[12] = true a hundred times, the set either contains the element 12, or it does not.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.