【问题标题】:Remove items from object array which has fields present in another array从对象数组中删除具有另一个数组中存在的字段的项目
【发布时间】:2020-07-07 10:59:54
【问题描述】:

我有一个如下数组:

selected = ["ID-1", "ID-2"];

还有一个对象数组,比如

objectArray = [
    {
        "id":"ID-1",
        "description":"Desction goes here",
        "another_filed":"Another Value"
    },
    {
        "id":"ID-2",
        "description":"Desction goes here",
        "another_filed":"Another Value"
    },
    {
        "id":"ID-3",
        "description":"Desction goes here",
        "another_filed":"Another Value"
    }
]

现在我需要从具有idobjectArray 中删除项目,它存在于selected 数组中。因此,在上述情况下,我需要从objectArray 中删除第一项和第二项,因为selected 变量中存在相应的 id,并且结果应该只有一个 id 值为 3 的对象。我怎么能这样做?

【问题讨论】:

  • objectArray = objectArray.filter(elem => !selected.includes(elem.id));
  • remove 是否意味着保持数组的相同对象引用?你试过什么吗?

标签: javascript arrays json typescript


【解决方案1】:

以下是一个可行的解决方案:

const selected = ["ID-1", "ID-2"]

const objectArray = [
  {
    id: "ID-1",
    description: "Desction goes here",
    another_filed: "Another Value",
  },
  {
    id: "ID-2",
    description: "Desction goes here",
    another_filed: "Another Value",
  },
  {
    id: "ID-3",
    description: "Desction goes here",
    another_filed: "Another Value",
  },
]

const res = objectArray.filter(({ id }) => !selected.includes(id))

console.log(res)

【讨论】:

    【解决方案2】:

    为什么不使用filter

    const selected = ["ID-1", "ID-2"];
    
    const objectArray = [
        {
            "id":"ID-1",
            "description":"Desction goes here",
            "another_filed":"Another Value"
        },
        {
            "id":"ID-2",
            "description":"Desction goes here",
            "another_filed":"Another Value"
        },
        {
            "id":"ID-3",
            "description":"Desction goes here",
            "another_filed":"Another Value"
        }
    ]
    
    const result = objectArray.filter(o => !selected.includes(o.id))
    
    console.log("result", result)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-18
      • 2019-11-23
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多