gpt4 book ai didi

javascript - 将 JSON 复制为模板

转载 作者:行者123 更新时间:2023-12-02 16:27:05 25 4
gpt4 key购买 nike

我有一个 json 模板,我用数据填充 - 在本例中是产品数据。例如我有以下 json

// 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 时,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
}
}

有什么想法可以实现这一点吗?任何建议将不胜感激。

此外,我想在每个“属性”对象中创建一个 ID 字段,例如(“ID”:“9e5670fa-2fd7-4858-a667-c99cb5baf0f9”)。是否可以使用 Angular 的 javascript 创建 guid?非常感谢

最佳答案

将变量设为数组并将对象插入数组中。

$scope.productAttributes = [];

var loadPrices = function () {
var item = {
code: $scope.productID.toUpperCase();
attributes: {
term: $scope.productAttributesObj.Term,
quantity: 1
}
}

$scope.productAttributs.push(item);
};

你可以让你的项目对象成为你需要的任何东西,我不知道你是如何获得所有东西的。但是将这些项目插入数组会给你你想要的东西。

关于javascript - 将 JSON 复制为模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28590222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com