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.

3
  • 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]; } Commented Sep 26, 2013 at 7:14
  • 1
    How about cloning an object, as per this answer Commented Sep 26, 2013 at 7: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... Commented Sep 26, 2013 at 7:45

1 Answer 1

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.