My function that removes properties from an object and returns a new one works fine, but it runs into issues when dealing with nested arrays of objects. How can I tackle this challenge?
interface User {
id: number;
name: string;
items?: User[];
}
const user: User = {
id: 1,
name: 'test',
items: [
{
id: 1,
name: 'item',
},
],
};
function adjustObject<T>(fields: (keyof T)[], obj: T): T {
const newObject = {} as T;
for (const key in obj) {
if (!fields.includes(key)) {
newObject[key] = obj[key];
}
if (Array.isArray(obj[key])) {
newObject[key] = [];
for (let j = 0; j < obj[key].length; j++) {
newObject[key].push(adjustObject(fields, obj[key][j]));
}
}
}
return newObject;
}
const result = adjustObject(['id'], user);
console.log(result);