如何用TypeScript/JavaScript动态移除JSON中的指定元素?
Let's say you have a JSON structure with nested careerLevels nodes (like your example input) and you want to remove this specific key from all relevant objects. Here are practical, easy-to-implement solutions:
Approach 1: Direct Deletion (Modifies Original Object)
If you don't mind altering the original data, you can loop through the array and delete the target key directly:
// Your sample input const input = { careerLevelGroups: [ { "201801": 58, "201802": 74, careerLevel: "Analyst", careerLevels: [ { "201801": 29, "201802": 37, careerID: "10000100" }, { "201801": 29, "201802": 37, careerID: "10000110" } ] }, { "201801": 58, "201802": 74, careerLevel: "Consultant", careerLevels: [ { "201801": 29, "201802": 37, careerID: "10000080" }, { "201801": 29, "201802": 37, careerID: "10000090" } ] } ] }; // Remove 'careerLevels' from each group input.careerLevelGroups.forEach(group => { delete group.careerLevels; }); console.log(input); // Output will have all careerLevelGroups without the careerLevels key
Approach 2: Immutable Removal (Preserves Original Object)
If you want to keep the original data intact, create a deep copy first, then modify the copy. This is safer for scenarios where you need the original data later:
// Deep copy using structuredClone (modern browsers/Node.js 17+) const inputCopy = structuredClone(input); // Remove the key from the copy inputCopy.careerLevelGroups.forEach(group => { delete group.careerLevels; }); console.log(inputCopy); // Modified version console.log(input); // Original remains unchanged
For environments that don't support structuredClone, you can use a recursive deep copy function:
function deepCopy<T>(obj: T): T { if (obj === null || typeof obj !== 'object') return obj; if (obj instanceof Array) return obj.map(item => deepCopy(item)) as unknown as T; const copiedObj = {} as T; for (const key in obj) { if (obj.hasOwnProperty(key)) { copiedObj[key] = deepCopy(obj[key]); } } return copiedObj; } // Usage const inputCopy = deepCopy(input); inputCopy.careerLevelGroups.forEach(group => delete group.careerLevels);
Generic Function for Any Target Key
To make this reusable for any key you want to remove (not just careerLevels), wrap the logic in a generic function:
function removeKeyFromArrayItems<T, K extends keyof T>( data: { careerLevelGroups: T[] }, keyToRemove: K ): { careerLevelGroups: Omit<T, K>[] } { // Create a deep copy to avoid mutating original const copiedData = structuredClone(data); copiedData.careerLevelGroups.forEach(group => { delete group[keyToRemove]; }); return copiedData; } // Usage: Remove 'careerLevels' const result = removeKeyFromArrayItems(input, 'careerLevels'); // Or remove another key like '201801' const resultWithout201801 = removeKeyFromArrayItems(input, '201801');
This function uses TypeScript generics to enforce type safety, ensuring you only pass valid keys for the objects in the array.
内容的提问来源于stack exchange,提问作者rp4361

