0

如何为每个通过.map的同一个数组创建两个相同的对象?

有一个如下的数据集:

data = [
  {initiatorRole: "dispatch", receiverRole: "police"},
  {initiatorRole: "dispatch", receiverRole: "fire"},
  {initiatorRole: "police", receiverRole: "dispatch"}
]

我想将这些放入一组对象中,我将在其中删除重复项并添加其他数据。

roles = [
  {role: "dispatch"},
  {role: "police"},
  {role: "dispatch",
  {role: "fire"},
  {role: "police"},
  {role: "dispatch"}
]

我目前拥有的代码:

roles = data.map(d => {
  let rObj = {}
  rObj["id"] = d.initiatorRole
  rObj["id"] = d.receiverRole
  return rObj;
});

但是当然这只是返回最后一个 rObj 集。这可以通过一个地图调用来完成吗?

4

3 回答 3

3

您可以将数组映射到两个角色的数组,并在同一步骤中使用 flatMap 将其展平,然后通过将其变为 Set 并返回数组来删除重复项:

roles = [...new Set(data.flatMap((d) => [d.initiatorRole, d.receiverRole]))]

那返回["dispatch", "police", "fire"]。这是 Observable notebook 中的一个演示

于 2021-09-02T13:03:41.147 回答
0

您可以使用 find 方法来查找它是否存在于结果中,您可以推送或忽略它

const myData = [
  {initiatorRole: "dispatch", receiverRole: "police"},
  {initiatorRole: "dispatch",  receiverRole: "fire"},
  {initiatorRole: "police", receiverRole: "dispatch"}
  ]

function flatAndRemoveDuplicate(data) {
  const result = [];
  
  for(let role of data) {
    const canfindInitiatorInResult = result.find(item => item.role == role.initiatorRole)
    const canfindReceiverResult = result.find(item => item.role == role.receiverRole)
     
    if(!canfindInitiatorInResult){
      result.push({role: role.initiatorRole})  
    }
    if(!canfindReceiverResult) {
            result.push({role: role.receiverRole})  
    }
  }
  return result;
}

console.log(flatAndRemoveDuplicate(myData))
   

于 2021-09-02T07:22:17.810 回答
0
data = [
  { initiatorRole: "dispatch", receiverRole: "police" },
  { initiatorRole: "dispatch", receiverRole: "fire" },
  { initiatorRole: "police", receiverRole: "dispatch" },
]

let rObj = []
data.forEach((d) => {
  rObj.push({ role: d.initiatorRole })
  rObj.push({ role: d.receiverRole })
})

const duplicateRemover = new Set()

const distinctArrObj = rObj.filter((obj) => {
  if (duplicateRemover.has(JSON.stringify(obj))) return false
  duplicateRemover.add(JSON.stringify(obj))
  return true
})

console.log(distinctArrObj)
于 2021-09-02T07:32:35.207 回答