Coffeescript:从json对象中删除重复值

时间:2014-08-18 11:53:38

标签: json coffeescript

我是咖啡脚本的新手。我知道这可能很傻。但不知道该怎么做。

我有一个Json对象。它可能有重复的对象。如何删除重复项并仅保留唯一对象。

    [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]

仅供参考:$$ hashkey不是我的json的一部分。当我安慰它时,我可以看到它 请帮忙, 感谢

2 个答案:

答案 0 :(得分:0)

Here就是如何实现这一目标的一个实例。

rows = [
  {id: "3", user: "jason"}
  {id: "4", user: "holmes"}
  {id: "4", user: "holmes"}
  {id: "5", user: "peter"}
]

# Use `id` as the key
# This will cause the duplicates to overwrite each other,
# and leave you with only one for each `id`
keyedRows = {}
for row in rows
  keyedRows[row.id] = row

# Convert back to an array
rowsDeDupped = (value for key, value of keyedRows)

alert(JSON.stringify(rowsDeDupped, null, 2))

注意,我假设您只需要识别重复的id。如果你想检查所有字段而不是这个字段,你必须采取不同的方法。

答案 1 :(得分:0)

基于{pure} coffeescript中id的重复数据删除:

rows = [
  {id: "3", user: "jason"}
  {id: "4", user: "holmes"}
  {id: "4", user: "holmes"}
  {id: "5", user: "peter"}
]

dedup = (value for _,value of new -> @[item.id] = item for item in rows; @)
#                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#                          create a new associative array (well ... "object") 
#                          using `item.id` as key. Duplicates will actually
#                          overwrite previous value for that key -- but this
#                          should be idempotent if `id` is a proper key.
console.log dedup

产:

[ { id: '3', user: 'jason' },
  { id: '4', user: 'holmes' },
  { id: '5', user: 'peter' } ]

如果您不喜欢“内联对象创建”,并且运行时支持Array.reduce,那么这可能是另一种选择:

dedup =
  (value for _,value of rows.reduce ((arr,value) -> arr[value.id] = value; arr),{})
相关问题