I'm trying to create a new object by using an already made object. This is what I am trying to achieve:
var obj = {"Name" : "Patrick", "Age": 25, "Country": "US"};
document.writeln(JSON.stringify(obj) + "<br />");
function Person(name, age, country) {
this.name = name;
this.age = age;
this.country = country;
}
document.writeln(JSON.stringify(new Person(obj)));
https://jsfiddle.net/dotjz9tb/
As you can see, I am trying to create a new person called Patrick, aged 25, who happens to live in the US. My Person constructor takes a name, an age, and a country as parameters. However, my object has already been created from a previous function, so I would like to do new Person(obj) and it would create a new object based on obj's parameters.
I know I can do new Person(obj.name, obj.age, obj.country) but I would rather pass the constructor an object instead, while still being able to do new Person("Jack", 52, "UK").
Is such thing possible? Right now this is how it's really being created:
new Person(obj, undefined, undefined);
//or
{
"name": {
"Name":" Patrick","
Age":25,
"Country":"US"
}
}
Meaning that age and country is set to nothing, while name is set to my object.
function Person(obj) { this.name = obj.Name; this.age = obj.Age; this.country = obj.Country; }arguments.length?