Howard Parr
Howard Parr

Reputation: 147

Javascript Nested Objects/Arrays Code Reduction Problem

I have an object for a collection of video data called "CollectionData". It has 3 key/value pairs:

collectionData.title - a simple string value
collectionData.seriesData - an array
collectionData.progressData - an array

Each of the 2 array values are objects:

collectionData.seriesData[x].title
collectionData.seriesData[x].year
collectionData.seriesData[x].length
collectionData.seriesData[x].synopsis

collectionData.progressData[x].currentTime
collectionData.progressData[x].progress

To save from having to type out collectionData.seriesData[x] or collectionData.progressData[x] every time to access the key's values I use a "pointer" into the object:

var p = collectionData.progressData[x];

I can then access the values of the keys by using p.currentTime, etc.

This works well if I want to replace a single key's value, i.e. p.currentTime = 25. However, if I want to replace the entire object's value, i.e. p = {currentTime:25,progress=10} the assignment operator does not evaluate the value of the variable p as a pointer into the object but as the pointer itself, therefore the object's value is not updated.

Is there a way to force the assignment operator to evaluate the variable p as a pointer or will I have to revert back to the full object name collectionData.progressData[x]={currentTime:25,progress=10}?

Upvotes: 1

Views: 28

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386680

You could take Object.assign and the new data which update the object.

const
    data = [{ currentTime: 1, progress: 1 }],
    p = data[0];

Object.assign(p, { currentTime: 25, progress: 10 });

console.log(data);

Upvotes: 1

Related Questions