[英]Adding a new object into a nested array
我想为每个嵌套数组添加一个新对象。 每当我将产品添加到订单中时,我都会调用此函数:
add2order(productID, productName, productRatePlans) {
this.orderIntake.push({ productID, productName, productRatePlans });
let i = 0;
this.orderIntake[0].productRatePlans[0].productRatePlanCharges.forEach(element => {
i++;
this.orderIntake[0].productRatePlans[0].productRatePlanCharges[
i
].quantity = this.orderIntake[0].productRatePlans[0].productRatePlanCharges[
i
].defaultQuantity;
});
}
这是服务器的示例响应:
{
"id": "8adc8f996928b9a4016929c59b943a8f",
"sku": "SKU-00006778",
"Partner_Account_ID__c": null,
"productRatePlans": [
{
"id": "8adce4216928c28d016929c59bff3372",
"status": "Active",
"name": "Enterprise",
"description": null,
"effectiveStartDate": "2016-02-26",
"effectiveEndDate": "2029-02-26",
"productRatePlanCharges": [
{
"id": "8adc8f996928b9a4016929c59d183a92",
"name": "USAGE_COUNTER_2",
"type": "Usage",
"model": "Volume",
"uom": "Each",
"pricingSummary": [
"Up to 5000 Each: USD0 flat fee"
],
"pricing": [
{
...
}
],
"defaultQuantity": null,
"applyDiscountTo": null,
"discountLevel": null,
"discountClass": null,
...
"financeInformation": {
..,
}
}
]
}
],
"productFeatures": [
{
...
}
]
}
正在从外部REST后端以这种方式检索数据,所以很遗憾,我无法初始化包括new属性的数据...
因此在每个productRatePlanCharges中应该有1个新对象“数量”。 如何将此字段添加到每个productRatePlanCharges? 现在我得到:错误
TypeError:无法读取未定义的属性“ productRatePlanCharges”
以及如何确保始终将其添加到最后一个orderIntake元素? 不要介意productRatePlans,每个订单中只有1个进货...
谢谢你的支持!
在这里,您必须使用如下所示的初始化数组来创建productDetails对象,以免出现错误。
add2order(productID, productName, productRatePlans) {
// Create object like below
let productDetails = { productID : productID, productName : productName, productRatePlans : productRatePlans
}
this.orderIntake.push(productDetails);
let i = 0;
this.orderIntake[0].productRatePlans[0].productRatePlanCharges.forEach(element => {
i++;
this.orderIntake[0].productRatePlans[0].productRatePlanCharges[
i
].quantity = this.orderIntake[0].productRatePlans[0].productRatePlanCharges[
i
].defaultQuantity;
});
}
希望这会有所帮助!
当您使用Angular时,您可能也使用了Typescript。 我建议您创建一个模型,例如传入模型,并在其中定义您的quantity: number
productRatePlanCharges对象中的quantity: number
。 然后将传入的数据映射到您自己的模型。 因此您的模型中的quantity=0
,以后可以在循环中进行更改。
如果要继续使用自己的方式,请看一下: 使用JavaScript向JSON对象添加新属性(元素)
几乎没有像您一样向当前模型添加元素的问题,并且问题可能出在其他地方,因为您的错误是指productRatePlanCharges的存在!
正如您以前所使用的,我更喜欢使用该“元素”并使用i++;
两次迭代i++;
对我来说不是一个好主意。 这可能会更好:
element.quantity = element.defaultQuantity;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.