【问题标题】:Coffeescript: Remove duplicate values from json objectCoffeescript:从 json 对象中删除重复值
【发布时间】:2014-10-11 07:56:23
【问题描述】:

我是咖啡脚本的新手。我知道这可能很愚蠢。但是不知道怎么弄。

我有一个 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 的一部分。当我安慰它时,我可以看到它。
请帮忙, 谢谢

【问题讨论】:

  • 你能举一个重复的例子吗?每个字段都会重复吗?只找到具有相同“$$hashKey”的就足够了吗?
  • 您能否提供一个SSCCE 示例和预期结果?
  • 或者您可以只使用一个实用程序库,例如下划线或 lodash:nonDupes = _(data).uniq (obj)-> obj.id jsfiddle:jsfiddle.net/3kskgbfy

标签: json coffeescript


【解决方案1】:

基于“纯”咖啡脚本中的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),{})

【讨论】:

    【解决方案2】:

    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。如果您想检查所有字段而不是只检查这个字段,则必须采用不同的方法。

    【讨论】:

    • @Sylvain,我一天的 Stack Overflow 时间快结束了,所以我想我会回答一些假设。在我的示例中,您可以通过将keyedRows[row.$$hashKey] 替换为keyedRows[row.id] 来解决该问题。希望这足以满足@Erma 的需要。
    • 完成。希望我没有犯错。
    猜你喜欢
    • 2012-11-25
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多