1

I want to save an array in an object in runtime through a loop.

For example, I take an input in an array inp=[2, 7, 20, 15, 19] and I want to save it in an obj={0:2, 1:7, 2:20, 3:15, 4:19}. But, at runtime such that I have a

    for(i=0;i<inp.length;i++) 
    { save each element of array into the respective object element } 

The problem is that I have to save arrays of different lengths, these array come from taking an input from user.

I am also sorting the object afterwards and returning the indices in another array in my code. I am stuck only at how to save an array in an object during runtime. I searched a lot for a clue to get started but, I could not find anything.

1
  • 3
    An Array already is an Object. Commented Apr 15, 2012 at 2:12

2 Answers 2

1
  • Autoassign: (credit: am not i am)

    var obj = inp.slice();
    
  • Manual Assignment:

    var obj = {};
    for(var i=0, n=inp.length; i<n; i++) 
       obj[i]=inp[i];
    

Though an Array is technically a subclass of an Object in JavaScript, the only thing that is really happening in going from an Array to an Object, is that you're losing the native methods (indexOf,concat,reverse,etc) that are created during the array's construction.

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

2 Comments

If you're going to copy it, you might as well do it the fast way var obj = inp.slice();
No problem, welcome to SO. If you found Derek or my answer helpful, give it an up vote and check off one of the answers that you found best answered your question. Upvotes/Checks are at no cost to your rating, in many cases, it helps increase your rating.
1

Array is already an object

If you do some experiments, you would find out:

typeof([]) //<--retruns "object"

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.