且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JS过滤器数组根据条件删除重复的值

更新时间:2022-03-14 06:18:13

您可以使用reduce并默认使用object,如果需要,可以将其转换为array

You can use reduce with default to object, and if you need, you can convert it to array at the end.

let myArray = [
     {role: "role-1", deviceId: ""},
     {role: "role-2", deviceId: "d-2"},
     {role: "role-3", deviceId: "d-3"},
     {role: "role-1", deviceId: "d-1"},
     {role: "role-2", deviceId: ""},
     {role: "role-4", deviceId: ""},
     {role: "role-5", deviceId: ""}
]

const res = myArray.reduce((agg, itr) => {
  if (agg[itr.role]) return agg // if deviceId already exist, skip this iteration
  agg[itr.role] = itr.deviceId  // if deviceId not exist, Add it
  return agg
}, {})

let make_array = Object.keys(res).map(key => { return { role: key, deviceId: res[key] }})

console.log(make_array)