Created
November 8, 2024 17:38
-
-
Save adamcee/dc95e1e8962f6a4349c4a3ac432084c8 to your computer and use it in GitHub Desktop.
JS map and filter method chaining example
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
| const fakePokemons = [ | |
| { name: 'Charizar', type: 'fire', isCaught: true}, | |
| { name: 'Pokemon', type: 'electric', isCaught: true}, | |
| { name: 'Ditto', type: 'normal', isCaught: false}, | |
| { name: 'Eevee', type: 'normal', isCaught: true}, | |
| ] | |
| /** | |
| * Creates and returns a new object which has all the same | |
| * properties as the poke object, but also has an `index` prop | |
| * and a `foo` prop | |
| * | |
| * @param {*} poke pokemon object | |
| * @param {*} index index int | |
| * @returns object | |
| */ | |
| const addStuffToPokeObject = (poke, index) => { | |
| return { | |
| ...poke, // destructures the obj into the object | |
| index: index, | |
| foo: 'hello' | |
| } | |
| }; | |
| const desired = 'normal' | |
| const desiredPokemonsWithFoo = fakePokemons | |
| .filter(p => p.type === desired) | |
| .filter(p => p.isCaught === true) | |
| // .map(addStuffToPokeObject); | |
| .map((p, i) => ({ ...p, index: i, foo: 'hello'})) | |
| console.log(desiredPokemonsWithFoo); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment