typescript 查找内部json并删除对象

wlp8pajw  于 2023-03-04  发布在  TypeScript
关注(0)|答案(1)|浏览(145)
{"apiKey":"11111","banKeys":["ip","userAgent"],"monitoringMode":{"isMonitoring":false,"dates":null},"pxg":{"trackingIds":[{"active":1,"pixelId":"12"},{"active":1,"pixelId":"123"}]}}

如何在这个JSON中搜索关键字pixelId?如果=12,则删除它所在的对象..因此,我将获得

{"apiKey":"11111","banKeys":["ip","userAgent"],"monitoringMode":{"isMonitoring":false,"dates":null},"pxg":{"trackingIds":[{"active":1,"pixelId":"123"}]}}

如果它是数组中唯一需要删除整个pxg对象的对象

{"apiKey":"11111","banKeys":["ip","userAgent"],"monitoringMode":{"isMonitoring":false,"dates":null}}

我需要用 typescript 来做
这是我在TS中的代码。但是我得到了一个错误

const data = {
  "apiKey": "11111",
  "banKeys": ["ip", "userAgent"],
  "monitoringMode": {
    "isMonitoring": false,
    "dates": null
  },
  "pxg": {
    "trackingIds": [
      {
        "active": 1,
        "pixelId": "12"
      },
      {
        "active": 1,
        "pixelId": "123"
      }
    ]
  }
};
        interface TrackingObject {
        active: number;
        pixelId: string;
    }

    interface PxgObject {
        trackingIds: TrackingObject[];
    }

    interface pixels {
        apiKey: string;
        banKeys: string[];
        monitoringMode: {
            isMonitoring: boolean;
            dates: null;
        };
        pxg?: PxgObject;
    }
const pixelIdToRemove = "12";

// Find the index of the object with the given pixelId
    const index: any = pixels.pxg.trackingIds.findIndex((obj: TrackingObject) => obj.pixelId === pixelId);

if (index !== -1) {
  // Remove the object at the found index
  data.pxg.trackingIds.splice(index, 1);

  // Remove the pxg object if the trackingIds array is empty
  if (data.pxg.trackingIds.length === 0) {
    delete data.pxg;
  }
}

console.log(data);
hc8w905p

hc8w905p1#

您的代码只是缺少类型:

type MonitoringModeType = {
    isMonitoring: boolean,
    dates: Date[] | null
}

type PxgType = {
    trackingIds: TrackingIdType[]
}

type TrackingIdType = {
    active: number,
    pixelId: string
}

type DataType = {
  apiKey: string,
  banKeys: string[],
  monitoringMode: MonitoringModeType,
  pxg: PxgType | undefined
}

const data: DataType = {
    "apiKey": "11111",
    "banKeys": ["ip", "userAgent"],
    "monitoringMode": {
        "isMonitoring": false,
        "dates": null
    },
    pxg: {
        "trackingIds": [
            {
                "active": 1,
                "pixelId": "12"
            },
            {
                "active": 1,
                "pixelId": "123"
            }
        ]
    }
};

const pixelIdToRemove = "12";

// Find the index of the object with the given pixelId
    const index: any = data.pxg?.trackingIds.findIndex((obj: TrackingIdType) => obj.pixelId === pixelIdToRemove);

if (index !== -1) {
  // Remove the object at the found index
  data.pxg?.trackingIds.splice(index, 1);

  // Remove the pxg object if the trackingIds array is empty
  if (data.pxg?.trackingIds.length === 0) {
    delete data.pxg;
  }
}

相关问题