You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native:如何合并重复用户项并在个人资料中展示?

对象数组按嵌套字段去重的解决方案

问题场景

原始用户数据:

{"name": "author-1", "slug": {"_type": "slug", "current": "author-1-slug"}}
{"name": "author-2", "slug": {"_type": "slug", "current": "author-2-slug"}}
{"name": "author-1", "slug": {"_type": "slug", "current": "author-1-slug"}}
{"name": "author-3", "slug": {"_type": "slug", "current": "author-3-slug"}}

期望去重后的结果:

{"name": "author-2", "slug": {"_type": "slug", "current": "author-2-slug"}}
{"name": "author-1", "slug": {"_type": "slug", "current": "author-1-slug"}}
{"name": "author-3", "slug": {"_type": "slug", "current": "author-3-slug"}}

尝试过的代码(未生效)

const filtered = _.uniqBy(authors, 'slug')

// 结果:[], [], [], []

问题原因

_.uniqBy(authors, 'slug') 失效的核心原因是:slug 是嵌套对象,lodash 默认比较的是对象的引用地址,而非对象内部的 current 值。即使两个 slug 对象内容完全一致,只要引用地址不同,就会被判定为不同元素,无法完成去重。

可行解决方案

方案1:基于 lodash 实现

直接指定以 slug.current 作为去重依据(字符串类型可被正确比较):

const filtered = _.uniqBy(authors, item => item.slug.current);

方案2:原生 JavaScript 实现

利用 Set 记录已出现的 slug.current 值,遍历数组过滤重复项:

const seen = new Set();
const filtered = authors.filter(item => {
  const slugCurrent = item.slug.current;
  if (!seen.has(slugCurrent)) {
    seen.add(slugCurrent);
    return true;
  }
  return false;
});

两种方案都能得到预期的去重结果,可根据项目是否依赖 lodash 自由选择。

内容的提问来源于stack exchange,提问作者BlackRain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 02:50:40