kar*_*and 2 javascript arrays dictionary unique object
我从 api 收到以下数据结构:
[
{
id: '10000844',
text_id: '10000844-01',
},
{
id: '10000844',
text_id: '10000844-02',
},
{
id: '12000844',
text_id: '12000844-03',
},
{
id: '12000844',
text_id: '12000844-07',
},
{
id: '12000814',
text_id: '12000844-07',
},
{
id: '12002812',
text_id: '12000844-07',
},
{
id: '12000814',
text_id: '12000844-08',
},
]
Run Code Online (Sandbox Code Playgroud)
清理代码的完美结果将是这样的结果,基本上只返回第一个找到的 id:
[
{
id: '10000844',
text_id: '10000844-01',
},
{
id: '12000844',
text_id: '12000844-03',
},
{
id: '12000814',
text_id: '12000844-07',
},
{
id: '12002812',
text_id: '12000844-07',
},
]
Run Code Online (Sandbox Code Playgroud)
但目前它仅返回唯一数组中最后找到的重复项,当前代码为:
let uniqueArray = [...new Map(data.map(item =>
[item.id, item])).values()];
Run Code Online (Sandbox Code Playgroud)
您可以使用Object.values()和reduce()相同:
const data = [
{
id: '10000844',
text_id: '10000844-01',
},
{
id: '10000844',
text_id: '10000844-02',
},
{
id: '12000844',
text_id: '12000844-03',
},
{
id: '12000844',
text_id: '12000844-07',
},
{
id: '12000814',
text_id: '12000844-07',
},
{
id: '12002812',
text_id: '12000844-07',
},
{
id: '12000814',
text_id: '12000844-08',
},
]
const result = Object.values(
data.reduce((res, {id, text_id}) => {
res[id] ??= {id, text_id}
return res
}, {})
)
console.log(result)Run Code Online (Sandbox Code Playgroud)
用文档更新??=
逻辑空赋值运算(x ??= y)符仅赋值if x is nullish (null or undefined)。
| 归档时间: |
|
| 查看次数: |
945 次 |
| 最近记录: |