假设我有一个简单的模型,如下:
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"}
]
};
答案 0 :(得分: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()
方法。
答案 1 :(得分: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;