0

I create an object with dynamic properties during runtime in JavaScript.

It simply works like that:

var object = {
    'time' = ""
};

After that, I'm able to add more properties, for instance, like that:

var propName = "value1";
object[propName] = "some content...";

But I need to work with a real object, so that I can create a new instance, e.g.: var myObject = NewObject('myTime', 'myValue1', 'myValue2' ...);

For creating a static custom object I would do this:

function NewObject(time, val1, val2, ... valn) {
    this.time = time;
    this.val1 = val1;
    ...
}

But I have no idea, how to design such a function dynamically, depending on different user input my NewObject could have 1 to n value properties...?

I know, I would be better to implement a List or Array, but I would like to know, if there's a solution for my problem?

Thanks for your help.

wassermine
  • 131
  • 1
  • 1
  • 9
  • 1
    can you create an array within your `NewObject`? For example, `this.vals = array(); for(i = 0; i < arguments.length; i++){ this.vals[i] = arguments[i]; }` – Zack Newsham Sep 26 '13 at 07:14
  • 1
    How about cloning an object, as per [this answer](http://stackoverflow.com/questions/122102/most-efficient-way-to-clone-an-object) – CodingIntrigue Sep 26 '13 at 07:15
  • thanks for your hints. I 'var newInstance = jQuery.extend({}, object);' worked in my case. But I will try @Passerby 's solution, because the jQuery.extend function might not work in every browser... – wassermine Sep 26 '13 at 07:45

1 Answers1

1

You can use the arguments object inside function:

function NewObject(time){
    this.time=time;
    if(arguments.length>1){
        for(var i=1;i<arguments.length;i++){
            this["val"+i]=arguments[i];
        }
    }
}

JSFiddle

Passerby
  • 9,715
  • 2
  • 33
  • 50