{"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);
1条答案
按热度按时间hc8w905p1#
您的代码只是缺少类型: