更新时间: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)