Reputation: 3715
I'm trying to create the following json object, I want to create the object with the tshirt name, and then after it's been created append a list of sizes to it.
{ tshirt: 'Vintage 80s',
size: { small: false },
size: { medium: false },
size: { large: true }
}
I can create the object easily with these lines of code
var availability = {};
availability.tshirt = "Vintage 80s";
but how would one go about appending each size to the object? this is for a node/express app, so I'd need a pure javascript solution. is there something like a .push for json objects as there as for arrays?
Upvotes: 0
Views: 1397
Reputation: 104775
You can set it just like how you set the tshirt
//Create an object of sizes
var sizes = {
small: false,
medium: false,
large: true
}
//Create your availability object.
var availability = {};
availability.tshirt = "Vintage 80s";
//Assign the sizes
availability.sizes = sizes;
//Log the results, change out small for medium or large
console.log(availability.sizes.small);
Upvotes: 1
Reputation: 16085
You have an object now with duplicate keys (size). I would propose to create another property "sizes" and add an array to it with objects, representing key value pairs for the sizes.
{ tshirt: 'Vintage 80s',
sizes: [{ small: false },
{ medium: false },
{ large: true }]
}
var availability = {};
availability.tshirt = "Vintage 80s";
availability.sizes = [{ small: false }, { medium: false }, { large: true }]];
Upvotes: 1
Reputation: 71918
You can't have multiple properties with the same name (like size
), but you can add all size objects to an array:
{
tshirt: 'Vintage 80s',
sizes: [
{ small: false },
{ medium: false },
{ large: true }
]
}
Note: that's not JSON, just a plain JavaScript object literal. JSON is a string notation to represent and exchange data.
Upvotes: 2
Reputation: 63472
Object keys are unique. You might want to use another object instead:
{ tshirt: 'Vintage 80s',
size: {
small: false,
medium: false,
large: true
}
}
You could then access the small size with something like:
availability.size.small
Upvotes: 4