2

I have thousands of legacy code that stores array information in a non array.

For example:

container.object1 = someobject;
container.object2 = someotherobject;
container.object3 = anotherone;

What I want to have is:

container.objects[1], container.objects[2], container.objects[3] etc.

The 'object' part of the name is constant. The number part is the position it should be in the array.

How do I do this?

asked Sep 23, 2011 at 17:28

3 Answers 3

6

Assuming that object1, object2, etc... are sequential (like an array), then you can just iterate through the container object and find all the sequential objectN properties that exist and add them to an array and stop the loop when one is missing.

container.objects = []; // init empty array
var i = 1;
while (container["object" + i]) {
 container.objects.push(container["object" + i]);
 i++;
}

If you want the first item object1 to be in the [1] spot instead of the more typical [0] spot in the array, then you need to put an empty object into the array's zeroth slot to start with since your example doesn't have an object0 item.

container.objects = [{}]; // init array with first item empty as an empty object
var i = 1;
while (container["object" + i]) {
 container.objects.push(container["object" + i]);
 i++;
}
answered Sep 23, 2011 at 17:33
Sign up to request clarification or add additional context in comments.

2 Comments

This will actually be slightly off from what was described. object1 will be objects[0] and not [1].
@kingjiv - I have addressed that issue. If they are going to use an array, I think they should change their logic to be like an array (with zero-based indexing), but they can have it either way.
2

An alternate way to do this is by using keys.

var unsorted = objectwithobjects;
var keys = Object.keys(unsorted);
var items = [];
for (var j=0; j < keys.length; j++) {
 items[j] = unsorted[keys[j]];
}

You can add an if-statement to check if a key contains 'object' and only add an element to your entry in that case (if 'objectwithobjects' contains other keys you don't want).

answered Sep 6, 2014 at 14:22

Comments

1

That is pretty easy:

var c = { objects: [] };
for (var o in container) {
 var n = o.match(/^object(\d+)$/);
 if (n) c.objects[n[1]] = container[o];
}

Now c is your new container object, where c.object[1] == container.object1

answered Sep 23, 2011 at 17:31

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.