Closed. This question needs details or clarity。它当前不接受答案。
想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
去年关闭。
我有一个这样的对象数组:
一或两个地址类型可能不存在,但总是带有
不知道该如何处理。有想法吗?
谢谢
想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
去年关闭。
我有一个这样的对象数组:
"addresses": [
{
"addressOrgName": "ACME",
"addressLine1": "1 BRAIDWOOD AVENUE",
"addressLine2": "KNUTSFORD",
"county": "CHESHIRE",
"postCode": "WA1 1QP",
"country": "UNITED KINGDOM",
"type": "DELIVERY",
"telephoneNumber" : "0151234533"
},
{
"addressOrgName": "ABC SUPPLIES",
"addressLine1": "UNIT 4 MILLENNIUM BUSINESS ESTATE",
"addressLine2": "BRUNTWOOD",
"county": "DEVON",
"postCode": "D1 5FG",
"country": "UNITED KINGDOM",
"type": "COLLECTION"
},
{
"addressOrgName": "EFG ELECTRICAL",
"addressLine1": "UNIT 4 MILLENNIUM BUSINESS ESTATE",
"addressLine2": "BRUNTWOOD",
"county": "DEVON",
"postCode": "D1 5FG",
"country": "UNITED KINGDOM",
"type": "RETURN"
}
]
一或两个地址类型可能不存在,但总是带有
type: DELIVERY
的地址类型。我需要完成的是检查是否存在以及哪一个不存在,并将缺少的一个推入数组,因此结果数组将如下所示:"addresses": [
{
"addressOrgName": "ADDRESSEE ONLY",
"addressLine1": "1 BRAIDWOOD AVENUE",
"addressLine2": "KNUTSFORD",
"county": "CHESHIRE",
"postCode": "WA1 1QP",
"country": "UNITED KINGDOM",
"type": "DELIVERY",
"telephoneNumber" : "0151234533"
},
{
"addressOrgName": "",
"addressLine1": "",
"addressLine2": "",
"county": "",
"postCode": "",
"country": "",
"type": "COLLECTION"
},
{
"addressOrgName": "",
"addressLine1": "",
"addressLine2": "",
"county": "",
"postCode": "",
"country": "",
"type": "RETURN"
}
]
不知道该如何处理。有想法吗?
谢谢
最佳答案
遍历每种需要的类型,如果找不到,则将其添加到数组中:
const addresses = [{
"addressOrgName": "EFG ELECTRICAL",
"addressLine1": "UNIT 4 MILLENNIUM BUSINESS ESTATE",
"addressLine2": "BRUNTWOOD",
"county": "DEVON",
"postCode": "D1 5FG",
"country": "UNITED KINGDOM",
"type": "RETURN"
}
];
const addTypes = ['DELIVERY', 'COLLECTION'];
addTypes.forEach((addType) => {
const foundObj = addresses.find(({ type }) => type === addType);
if (foundObj) return;
addresses.push({
"addressOrgName": "",
"addressLine1": "",
"addressLine2": "",
"county": "",
"postCode": "",
"country": "",
"type": addType,
});
});
console.log(addresses);