繁体   English   中英

javascript - 从对象中的所有实例中删除特定键

[英]javascript - remove a specific key from all instances in an object

我嵌套了 JS 对象,这些对象是从 webmethod (C#) 中获取的,例如:

{
  "__type": "App.ApplePay.PaymentRequest",
  "countryCode": "US",
  "currencyCode": "USD",
  "lineItems": [
    {
      "label": "Product Title here",
      "amount": "3600.00",
      "type": "final"
    },
    {
      "label": "Subtotal",
      "amount": "3600.00",
      "type": "final"
    },
    {
      "label": "Complimentary Express Delivery",
      "amount": "0.00",
      "type": "final"
    },
    {
      "label": "Estimated Tax",
      "amount": "0.00",
      "type": "final"
    }
  ],
  "total": {
    "label": "Shop Name",
    "amount": "3600.00"
  },
  "supportedNetworks": [
    "masterCard",
    "visa",
    "discover"
  ],
  "merchantCapabilities": [
    "supports3DS"
  ],
  "shippingMethods": [
    {
      "label": "Complimentary Express Delivery",
      "amount": "0.00",
      "identifier": "exp-delivery-free",
      "detail": "complimentary express delivery"
    }
  ],
  "shippingContact": {
    "__type": "App.ApplePay.ContactInfo",
    "phoneNumber": null,
    "emailAddress": null,
    "givenName": null,
    "familyName": null,
    "phoneticGivenName": null,
    "phoneticFamilyName": null,
    "addressLines": null,
    "subLocality": null,
    "locality": null,
    "postalCode": null,
    "subAdministrativeArea": null,
    "administrativeArea": null,
    "country": null,
    "countryCode": null
  },
  "requiredBillingContactFields": [
    "email",
    "phone",
    "postalAddress"
  ],
  "requiredShippingContactFields": [
    "email",
    "phone",
    "postalAddress"
  ],
  "shippingContactEditingMode": null
}

期望输出:

  1. 我想从所有对象的任何深处删除__type属性。 对象可以嵌套在对象中,也可以嵌套在数组中。
  2. 我想从所有对象的任何深处删除值为 Null 或 Empty 的属性。
  3. 如果属性是对象(例如shippingContact)并且其中的所有值都为null,则删除主键,即shippingContact。

 const apiObject = { "__type": "App.ApplePay.PaymentRequest", "countryCode": "US", "currencyCode": "USD", "lineItems": [ { "label": "Product Title here", "amount": "3600.00", "type": "final" }, { "label": "Subtotal", "amount": "3600.00", "type": "final" }, { "label": "Complimentary Express Delivery", "amount": "0.00", "type": "final" }, { "label": "Estimated Tax", "amount": "0.00", "type": "final" } ], "total": { "label": "Shop Name", "amount": "3600.00" }, "supportedNetworks": [ "masterCard", "visa", "discover" ], "merchantCapabilities": [ "supports3DS" ], "shippingMethods": [ { "label": "Complimentary Express Delivery", "amount": "0.00", "identifier": "exp-delivery-free", "detail": "complimentary express delivery" } ], "shippingContact": { "__type": "App.ApplePay.ContactInfo", "phoneNumber": null, "emailAddress": null, "givenName": null, "familyName": null, "phoneticGivenName": null, "phoneticFamilyName": null, "addressLines": null, "subLocality": null, "locality": null, "postalCode": null, "subAdministrativeArea": null, "administrativeArea": null, "country": null, "countryCode": null }, "requiredBillingContactFields": [ "email", "phone", "postalAddress" ], "requiredShippingContactFields": [ "email", "phone", "postalAddress" ], "shippingContactEditingMode": null }; function sanitizeObject(obj) { for (var propName in obj) { if (!obj.hasOwnProperty(propName)) continue; if(!Array.isArray(obj[propName]) && typeof obj[propName] == "object"){ sanitizeObject(obj[propName]); } else if(propName == "__type" || obj[propName] == null || obj[propName] == "undefined" || obj[propName] == ""){ delete obj[propName]; } } return obj; } console.log(sanitizeObject(apiObject));

但似乎没有按预期工作。 有什么帮助吗?

这应该有效。 如果需要,请不要犹豫进一步解释。

function sanitizeObject (obj) {
  if(Array.isArray(obj)){
    obj = obj.map(item=>sanitizeObject(item)).filter(item=>item);
    if(obj.length===0) obj = 'undefined';
  } else if(typeof obj === 'object'){
    let empty = true;
    Object.keys(obj).forEach(key=>{
      if(!obj[key] || key==="__type"){
        obj[key] = undefined;
      } else {
        obj[key] = sanitizeObject(obj[key]);
        if(obj[key]) empty = false;
      }
    });
    if(empty) obj = 'undefined';
  }
  return obj;
}

目前您正在处理递归调用案例并删除目标属性...

if(!Array.isArray(obj[propName]) 
    && typeof obj[propName] == "object")
{
   // recursion   
} else if(propName == "__type" || ....)
{
   // delete
}

但是,您没有处理属性值为数组的情况。 在这种情况下,您需要遍历对象数组

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM