【问题标题】:filter array of object and add extra filed for duplicate value?过滤对象数组并为重复值添加额外字段?
【发布时间】:2021-12-27 11:46:58
【问题描述】:

我有一个对象数组。我想按两个键过滤,如果有任何重复项需要添加额外的键,包括详细信息 例如

[
    {
        "start": 0,
        "end": 38,
        "content": "announcing improvements to the GitHub "
    },
    
    {
        "uuid": "6f08b9df-7b07-4da9-bbe0-8c93d5d0a19b",
        "start": 51,
        "end": 59,
        "entity_type": "class1",
        "content": "Workflow"
    },
    {
        "uuid": "21dffe1c-0f8c-4c13-8bee-6185fb15cbd8",
        "start": 51,
        "end": 59,
        "entity_type": "class2",
        "content": "Workflow"
    },
    {
        "start": 59,
        "end": 101,
        "content": "” experience. Now, when you want to create"
    }
]

预期的输出是

let excepted = [
    {
        "start": 0,
        "end": 38,
        "content": "announcing improvements to the GitHub "
    },
    {
        "uuid": ["6f08b9df-7b07-4da9-bbe0-8c93d5d0a19b","21dffe1c-0f8c-4c13-8bee-6185fb15cbd8"],
        "start": 51,
        "end": 59,
        "isDuplicate":true,
        "labels":["class2","class1"],
        "content": "Workflow"
    },
    {
        "start_offset": 59,
        "end": 101,
        "content": "” experience. Now, when you want to create"
    }
]

在上面的示例中,您可以看到键开始 51 和结束 59 在输出中有两个重复条目,我想像在输出标签中一样聚合两者

【问题讨论】:

  • 请添加您的代码。出了什么问题?
  • 只要在 SO 上搜索"array of objects group by key",您就会发现很多对您有帮助的问题和答案。它们不会完美地解决您的问题,但通过一些细微的调整,您将获得您想要的解决方案。
  • 请展示你做了什么

标签: javascript arrays


【解决方案1】:

只是有点不同的结果,而不是"labels":["class2","class1"] 它是"entity_type":["class2","class1"]

const arr = [{"start": 0,"end": 38,"content": "announcing improvements to the GitHub "},{"uuid": "6f08b9df-7b07-4da9-bbe0-8c93d5d0a19b","start": 51,"end": 59,"entity_type": "class1","content": "Workflow"},{"uuid": "21dffe1c-0f8c-4c13-8bee-6185fb15cbd8","start": 51,"end": 59,"entity_type": "class2","content": "Workflow"},{"start": 59,"end": 101,"content": "” experience. Now, when you want to create"}]
    
const reduced = arr.reduce((acc, obj) => {
  const hash = `${obj.start}-${obj.end}`;
  if (acc[hash]) {
    acc[hash] = {
      ...acc[hash],
      isDuplicate: true,
      uuid: Array.isArray(acc[hash].uuid) 
        ? [obj.uuid]
        : [acc[hash].uuid, obj.uuid],
      entity_type: Array.isArray(acc[hash].entity_type) 
        ? [obj.entity_type]
        : [acc[hash].entity_type, obj.entity_type],
    };
  } else {
    acc[hash] = { ...obj };
  }
  return acc;
}, {});
const result = Object.values(reduced);

console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-10
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-02
    • 2020-07-20
    相关资源
    最近更新 更多