Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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