Last active
January 3, 2017 15:43
-
-
Save davidsharp/018e60c37d66c60f247a971c6063a2eb to your computer and use it in GitHub Desktop.
A quick, dirty helper function swapping arrays of nested objects for objects tracked by ID
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 normyHelper = (...args) => { | |
| const obj = {}; | |
| ( args[1] && /string/.test(typeof args[0]) ? args[1].map(c=>c[args[0]]) : args[0] ) | |
| .forEach((c,i)=>{obj[(c.id?c.id:i)]=c}); | |
| return obj; | |
| } | |
| //> normyHelper('foo', [ {foo:{name:'foobar',id:1}}, {foo:{name:'barbaz',id:2}} ]) | |
| // { '1': { name: 'foobar', id: 1 }, | |
| // '2': { name: 'barbaz', id: 2 } } | |
| //> normyHelper([ {name:'foobar',id:1}, {name:'barbaz',id:2} ]) | |
| // { '1': { name: 'foobar', id: 1 }, | |
| // '2': { name: 'barbaz', id: 2 } } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I realised that I don't always have nested items, so I've updated it with an even hackier looking version that takes either two params (string and array) or just one param (array)