Skip to content

Instantly share code, notes, and snippets.

@tangentstorm
Created December 2, 2020 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tangentstorm/b3b0a66d38c2ffce2546e60b4b826d32 to your computer and use it in GitHub Desktop.
Save tangentstorm/b3b0a66d38c2ffce2546e60b4b826d32 to your computer and use it in GitHub Desktop.
meld a list of dictionaries into a smaller list of dictionaries
glue = (x,y) => x === undefined ? y : Array.isArray(x) ? x.concat(y) : [x,y]
function meld(xs) {
let idx = {}, res = [], it
for (x of xs) {
if (x.id in idx) it = res[idx[x.id]]
else { it = {id: x.id}; idx[x.id] = res.length; res.push(it) }
for (k of Object.keys(x)) if (k!=='id') it[k] = glue(it[k], x[k]) }
return res }
JSON.stringify(meld([
{a: 'abcd', id: '1'},
{b: 'bcd', id: '2'},
{c: 'cded', id: '3'},
{d: 'abc', id: '4'},
{a: 'abc', id: '1'},
{c: 'cde', id: '3'},
{a: 'abcde', id: '1'}]))
// "[{"id":"1","a":["abcd","abc","abcde"]},{"id":"2","b":"bcd"},{"id":"3","c":["cded","cde"]},{"id":"4","d":"abc"}]"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment