Last active
December 18, 2021 09:35
-
-
Save shawn-dsz/af7625db5a6e962c892585b0d0d2835e to your computer and use it in GitHub Desktop.
recursively add prop to array objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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