[英]appending/push to json object
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. 我正在尝试创建以下json对象,我想使用tshirt名称创建该对象,然后在创建该对象后为其添加尺寸列表。
{ 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. 这是用于node / express应用的,所以我需要一个纯JavaScript解决方案。 is there something like a .push for json objects as there as for arrays? 是否有像.push这样的json对象以及数组对象?
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
You can't have multiple properties with the same name (like size
), but you can add all size objects to an array: 您不能具有相同名称的多个属性(例如size
),但是可以将所有size对象添加到数组中:
{
tshirt: 'Vintage 80s',
sizes: [
{ small: false },
{ medium: false },
{ large: true }
]
}
Note: that's not JSON, just a plain JavaScript object literal. 注意:这不是JSON,只是普通的JavaScript对象文字。 JSON is a string notation to represent and exchange data. JSON是用于表示和交换数据的字符串符号。
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. 我建议创建另一个属性“ 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 }]];
You can set it just like how you set the tshirt
您可以像设置T 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.