1

假设我有一个简单的模型,如下所示:

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

但是我将如何将一个新对象插入到现有对象中呢?假设我制作了一个新对象:

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

我需要动态生成各种模型并将它们插入模型的各个部分。

我的最终模型如下所示:

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

2 回答 2

3

我不确定我是否完全理解您的问题,但我如何理解它,您需要做的就是设置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;

您也可以使用 EMCAScript 5 的Object.create()方法。

于 2012-09-11T21:24:31.883 回答
0

在 person 中创建一个数组:

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

或者

var pets = [{name: "Lucky", type: "Dog"}, {name: "Paws", type: "Cat"}];
person.pets = pets;
于 2012-09-11T21:24:20.587 回答