gpt4 book ai didi

javascript - 将对象推送到数组并使用另一个对象作为属性

转载 作者:太空宇宙 更新时间:2023-11-04 16:26:58 24 4
gpt4 key购买 nike

我想根据数据表行创建 json 字符串。下面的源代码运行良好,但有时我没有 AddressDetails 对象,并且我不想设置它。如何向此代码添加条件(如果 selectedRow.DeliveryAddressDetails=null 未设置 DeliveryAddressDetails )

var returnItems=[];
data.each(function() {
var rowIndex = $dataTable.fnGetPosition(this);
var selectedRow = $dataTable.fnGetData(rowIndex);
returnItems.push(
{
DeliveryAddress: selectedRow.DeliveryAddress,
Extension: selectedRow.Extension,
IsCourier: selectedRow.IsCourier,
Quantity: selectedRow.Quantity,
DeliveryAddressDetails: {
AddressDestinationDescription: selectedRow.DeliveryAddressDetails.AddressDestinationDescription,
AddressDestinationDetailId: selectedRow.DeliveryAddressDetails.AddressDestinationDetailId,
AddressDestinationName: selectedRow.DeliveryAddressDetails.AddressDestinationName,
AddressLine1: selectedRow.DeliveryAddressDetails.AddressLine1,
AddressLine2: selectedRow.DeliveryAddressDetails.AddressLine2,
AddressLine3: selectedRow.DeliveryAddressDetails.AddressLine3,
CityName: selectedRow.DeliveryAddressDetails.CityName,
PhoneNumber: selectedRow.DeliveryAddressDetails.PhoneNumber,
ZipCode: selectedRow.DeliveryAddressDetails.ZipCode
}
});
});
$("#myJson").val(JSON.stringify(returnItems));

感谢帮助

最佳答案

您必须先创建对象,然后有条件地添加该属性

var returnItems = [];
data.each(function() {
var rowIndex = $dataTable.fnGetPosition(this);
var selectedRow = $dataTable.fnGetData(rowIndex);
var obj = {
DeliveryAddress: selectedRow.DeliveryAddress,
Extension: selectedRow.Extension,
IsCourier: selectedRow.IsCourier,
Quantity: selectedRow.Quantity
}
if ( DeliveryAddressDetails !== null ) { // or typeof ** == "object"
obj.DeliveryAddressDetails = {
AddressDestinationDescription: selectedRow.DeliveryAddressDetails.AddressDestinationDescription,
AddressDestinationDetailId: selectedRow.DeliveryAddressDetails.AddressDestinationDetailId,
AddressDestinationName: selectedRow.DeliveryAddressDetails.AddressDestinationName,
AddressLine1: selectedRow.DeliveryAddressDetails.AddressLine1,
AddressLine2: selectedRow.DeliveryAddressDetails.AddressLine2,
AddressLine3: selectedRow.DeliveryAddressDetails.AddressLine3,
CityName: selectedRow.DeliveryAddressDetails.CityName,
PhoneNumber: selectedRow.DeliveryAddressDetails.PhoneNumber,
ZipCode: selectedRow.DeliveryAddressDetails.ZipCode
}
}
returnItems.push();
});

$("#myJson").val(JSON.stringify(returnItems));

关于javascript - 将对象推送到数组并使用另一个对象作为属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40137365/

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