Coffeescript: Remove duplicate values from json object -
i new coffee script. know might silly. don't know how it.
i have json object. may have duplicate objects. how can remove duplicates , keep unique objects only.
[object, object, object, object] 0: object $$hashkey: "045" id: "2" user: "mark" __proto__: object 1: object $$hashkey: "046" id: "3" user: "jason" __proto__: object 2: object $$hashkey: "047" id: "4" user: "holmes" __proto__: object 3: object $$hashkey: "048" id: "5" user: "peter" __proto__: object 4: object $$hashkey: "04d" id: "4" user: "holmes" __proto__: object length: 5 __proto__: array[0]
fyi : $$hashkey not part of json. when console see it.
please help, thanks
deduplication based on id
in "pure" coffeescript:
rows = [ {id: "3", user: "jason"} {id: "4", user: "holmes"} {id: "4", user: "holmes"} {id: "5", user: "peter"} ] dedup = (value _,value of new -> @[item.id] = item item in rows; @) # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # create new associative array (well ... "object") # using `item.id` key. duplicates # overwrite previous value key -- # should idempotent if `id` proper key. console.log dedup
producing:
[ { id: '3', user: 'jason' }, { id: '4', user: 'holmes' }, { id: '5', user: 'peter' } ]
if don't "inline object creation", , if runtime supports array.reduce
might alternative:
dedup = (value _,value of rows.reduce ((arr,value) -> arr[value.id] = value; arr),{})
Comments
Post a Comment