Jedediah
Jedediah

Reputation: 1944

Dynamically insert object into existing object

Lets say I have a simple model, like this:

var person = {
    name: "Bob",
    age: "30"
}

But how would I go about inserting a new object into the existing one? Say I make a new object:

var pets = [{name: "Lucky", type: "Dog"}, {name: "Paws", type: "Cat"}];

I will need to dynamically generate various models and insert them into various sections of my model.

My final model would look like this:

var person = {
        name: "bob",
        age: "30",
        pets: [
            {name: "Lucky", type: "dog"},
            {name: "Paws", type: "Cat"}
        ]
    };

Upvotes: 1

Views: 100

Answers (2)

jeremy
jeremy

Reputation: 10057

I'm not sure I completely understand your question, but how I understand it, all you need to do is set a new attribute of person.

var person = {
        name: "Bob",
        age: "30"
    },
    pets = [{ name: "Lucky", type: "Dog" }, { name: "Paws", type: "Cat" }];

person.pets = pets;

console.log(person); // Object: (String) name, (String) age, (Array) pets;

You could also use EMCAScript 5's Object.create() method.

Upvotes: 3

Austin Greco
Austin Greco

Reputation: 33554

create an array within person:

person.pets = [
   {name: "Lucky", type: "dog"},
   {name: "Paws", type: "Cat"}
];

or

var pets = [{name: "Lucky", type: "Dog"}, {name: "Paws", type: "Cat"}];
person.pets = pets;

Upvotes: 0

Related Questions