Javascript 将JSON复制为模板
我有一个用数据填充的json模板——在本例中是产品数据。例如,我有以下jsonJavascript 将JSON复制为模板,javascript,json,angularjs,Javascript,Json,Angularjs,我有一个用数据填充的json模板——在本例中是产品数据。例如,我有以下json // product template $scope.productAttributes = { "Code": null, 'Attributes': {} }; 当用户通过Ui输入一些产品详细信息并调用loadPrices()时,我将使用此函数填充productAttributes var loadPrices = function () {
// product template
$scope.productAttributes = {
"Code": null,
'Attributes':
{}
};
当用户通过Ui输入一些产品详细信息并调用loadPrices()时,我将使用此函数填充productAttributes
var loadPrices = function () {
$scope.entity = {// grabs variables from a form};
$scope.productAttributes.Code = $scope.productID.toUpperCase();
$scope.productAttributes.Attributes = $scope.entity;
$scope.productAttributes.Attributes.Term = $scope.productAttributesObj.Term;
$scope.productAttributes.Attributes.Quantity = 1;
};
这是productAttributes的结果
{
"Code": "CON7",
"Attributes": {
"Postcode": "n44er",
"rSize": 1000,
"Bandwidth": 10,
"Term": "36",
"Quantity": 1
}
}
所以我的问题是,每当我试图通过调用loadPrices添加新数据时,productAttributes都会被覆盖。我希望创造一个这样的结构
{
"Code": "CON7",
"Attributes": {
"Postcode": "n44er",
"Size": 1000,
"Bandwidth": 10,
"Term": "36",
"Quantity": 1
},
"Code": "CON34",
"Attributes": {
"Postcode": "nww45",
"Size": 10,
"Bandwidth": 10,
"Term": "36",
"Quantity": 1
},
"Code": "CON89",
"Attributes": {
"Postcode": "sw23ed",
"Size": 101,
"Bandwidth": 101
}
}
有什么办法可以做到这一点吗?如有任何建议,将不胜感激
此外,我还想在每个“Attributes”对象中创建一个ID字段,例如(“ID”:“9e5670fa-2fd7-4858-a667-c99cb5baf0f9”)。是否可以使用Java脚本创建GUI?非常感谢将变量设置为数组并将对象推入数组
$scope.productAttributes = [];
var loadPrices = function () {
var item = {
code: $scope.productID.toUpperCase();
attributes: {
term: $scope.productAttributesObj.Term,
quantity: 1
}
}
$scope.productAttributs.push(item);
};
你可以让你的物品对象成为你需要的任何东西,我不知道你是如何拥有一切的。但是,将这些项目放入阵列将为您提供所需的内容。尝试以下方法:
var loadPrices = function () {
$scope.entity = {/* grabs variables from a form*/};
var myEntity = {};
myEntity.Code = $scope.productID.toUpperCase();
myEntity.Attributes = $scope.entity;
myEntity.Attributes.Term = $scope.productAttributesObj.Term;
myEntity.Attributes.Quantity = 1;
$scope.productAttributes.push(myEntity);
};
不要忘记将$scope.productAttributes声明为数组
$scope.productAttributes = [];
顺便说一句,关于json操作的更多信息:
您的JSON看起来无效,因为您在同一对象中多次使用同一密钥。这就是为什么您看到您的值被覆盖。