Skip to content

Instantly share code, notes, and snippets.

@shawn-dsz
Last active December 18, 2021 09:35
Show Gist options
  • Save shawn-dsz/af7625db5a6e962c892585b0d0d2835e to your computer and use it in GitHub Desktop.
Save shawn-dsz/af7625db5a6e962c892585b0d0d2835e to your computer and use it in GitHub Desktop.
recursively add prop to array objects
// interface Topping {
// // name: string;
// id: number;
// subOptions?: Topping[];
// checked?: boolean;
// }
const toppings = [
{
id: 1,
subOptions: [{ id: 2, subOptions: [{ id: 3 }] }],
},
{
id: 2,
subOptions: [],
},
{ id: 3, subOptions: [{ id: 5 }] },
];
// function removeMeta(obj) {
// for (prop in obj) {
// if (prop === '$meta') delete obj[prop];
// else if (typeof obj[prop] === 'object') removeMeta(obj[prop]);
// }
// }
function recurse(toppingOption) {
const newToppings = [];
// base case, to break the recursion when the array is empty
if (toppingOption.length === 0) {
return [];
}
for (const topping of toppingOption) {
if (topping.subOptions) {
const top = recurse(topping.subOptions);
topping.subOptions = top;
}
newToppings.push({ ...topping, checked: false });
}
// Do something to x
return newToppings;
}
recurse(toppings);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment