Skip to content

Instantly share code, notes, and snippets.

@davidsharp
Last active January 3, 2017 15:43
Show Gist options
  • Select an option

  • Save davidsharp/018e60c37d66c60f247a971c6063a2eb to your computer and use it in GitHub Desktop.

Select an option

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
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 } }
@davidsharp

Copy link
Copy Markdown
Author

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment