1

I want to create a json object like:

{
   name: "Julia"
   birthdate: "xxxx"
   movies: [{title: "movie1", rating: 5}, {title: "movie2", rating 3}}]
}

I want to do something like:

var myobj = [];
myobj.push({name: "Julia", birthdate: "xxxx"});

myobj.movies = [];
myobj.movies.push({title: "movie1", rating: 5});
myobj.movies.push({title: "movie2", rating: 3});

But I am unable to create that "movies" part. How do I accomplish this?

0

3 Answers 3

8

You are getting this error because you are creating the object as an array. You have to create as an object to add properties:

var myobj = {name: "Julia", birthdate: "xxxx"};

myobj.movies = []; 
myobj.movies.push({title: "movie1", rating: 5}); 
myobj.movies.push({title: "movie2", rating: 3}); 
Sign up to request clarification or add additional context in comments.

Comments

1

You cannot mix datatypes(push works only on Arrays and attributes with objects), try something like this:

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});

Comments

1

ye this works

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.