Reputation: 27703
Say I want the object to be something like this:
var Book = {
title: "the catcher in the rye",
price: "80.98",
characters: [{name: "holden caulfield", age: 16, height:"6.2"},
{name: "phoebe caulfield",age:13, height: "5"}]
};
EDITED
question: characters array is built by adding a character one by one. How can do this while making sure that name, age and height properties are defined as above.
Something to the effect of?
Book.characters.add({name: "phoebe caulfield",age:13, height: "5"});
I would like to be able to define this programmatically, ie add properties to the object rather than define it like this.
Is this possible?
Upvotes: 3
Views: 6953
Reputation: 2560
using the map function is the easiest way I've found to build an array of objects. The snippet below, constructs the objet you want in just 2 statements:
var Book = {
title: "the catcher in the rye",
price: 80.98
};
Book.characters = [6.2, 5].map(el => {
return {
name: 'caulfield', age: 14, height: el
};
});
// Output
JSON.stringify(Book);
{
"title": "the catcher in the rye",
"price": 80.98,
"characters": [
{ "name":"caulfield", "age":14, "height":6.2 },
{ "name":"caulfield", "age":14, "height":5 }
]
}
Upvotes: 0
Reputation: 3761
I think you're looking for a JSON stringifier: http://www.json.org/js.html
This will allow you to create your object:
var myobj = { };
myobj.myprop = "value";
alert(JSON.stringify(myobj));
Upvotes: 0
Reputation: 38103
It certainly is! Javascript is a completely dynamic language - if you want a new property on an object, just set it!
e.g.
var myObject = {}; // empty object
myObject.myProperty = 5; // creates the new property and sets it to 5.
myObject.nestedObject = { prop1: 6, 'long-property-name': 'lolcats' };
Upvotes: 0
Reputation: 4079
var Book={};
Book.title="the catcher in the rye";
Book.price="80.98";
var characters=[];
characters.push({name: "holden caulfield", age: 16, height:"6.2"});
characters.push({name: "phoebe caulfield",age:13, height: "5"});
Book.characters=characters;
...etc.
Upvotes: 0
Reputation: 707158
You can do it in dynamic code (rather than a static declaration) like this:
var Book = {};
Book.title = "the catcher in the rye";
Book.price = "80.98";
Book.characters = [];
Book.characters.push({name: "holden caulfield", age: 16, height: "6.2"});
Book.characters.push({name: "phoebe caulfield", age: 13, height: "5"});
Upvotes: 7
Reputation: 164730
Do you mean like this?
var Book = {}; // empty object
Book.title = "the catcher in the rye";
Book.price = 80.98;
Book.characters = [];
var character = {
"name": "holden caulfield",
"age": 16,
"height": 6.2
};
Book.characters.push(character);
Upvotes: 2