Question

For my web-application I would like to add an object before another object inside a self-defined object.... I did find the insertBefore method, but it only applies to DOM objects. The object looks like:

objTemplate[0].objEntry;
objTemplate[1].objEntry;
                    <= add objEntry here
objTemplate[2].objEntry;
objTemplate[3].objEntry;

Now I would like to add a new instance of objEntry before entry 2 in objTemplate. How can I do that?

Was it helpful?

Solution

Assuming objTemplate is an array you can use Array.prototype.splice:

objTemplate.splice(2, 0, objEntry);

Or, if, for whatever reason, it's not a real array (and you're using numerical indexes) then you can still use splice the following way:

Array.prototype.splice.call(objTemplate, 2, 0, objEntry);

This will work for "array-like" objects - note that your object must have a length property.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top