我想创建一个json对象,如:
{
name: "Julia"
birthdate: "xxxx"
movies: [{title: "movie1", rating: 5}, {title: "movie2", rating 3}}]
}
我想做类似的事情:
var myobj = [];
myobj.push({name: "Julia", birthdate: "xxxx"});
myobj.movies = [];
myobj.movies.push({title: "movie1", rating: 5});
myobj.movies.push({title: "movie2", rating: 3});
但我无法创造“电影”部分。我该如何做到这一点?
答案 0 :(得分:7)
您收到此错误是因为您正在将对象创建为数组。您必须创建一个对象来添加属性:
var myobj = {name: "Julia", birthdate: "xxxx"};
myobj.movies = [];
myobj.movies.push({title: "movie1", rating: 5});
myobj.movies.push({title: "movie2", rating: 3});
答案 1 :(得分:1)
你不能混合数据类型(推送仅适用于数组和属性与对象),尝试这样的事情:
var myobj = {};
myobj.persons = [];
myobj.persons.push({name: "Julia", birthdate: "xxxx"});
myobj.movies = [];
myobj.movies.push({title: "movie1", rating: 5});
myobj.movies.push({title: "movie2", rating: 3});
答案 2 :(得分:0)
这是有效的
var myobj = [];
myobj.push({name: "Julia", birthdate: "xxxx"});
myobj.push({movies: []});
myobj.movies = [];
myobj.movies.push({title: "movie1", rating: 5});
myobj.movies.push({title: "movie2", rating: 3});
console.log(myobj);</code>