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

如何使用ES6识别数组中共享一个或多个属性值的对象?

问题描述

我有一个对象数组需要展示:

const items = [
{
  id: 584,
  title: "spaceships",
  tags: ["space"],
},
{
  id: 372,
  title: "children's space",
  tags: ["children", "space"],
},
{
  id: 546,
  title: "teddy bears at the beach",
  tags: ["teddy bears", "beach"],
},
{
  id: 549,
  title: "children's toys",
  tags: ["children", "toys"],
}]

展示单个项目时,我希望同时显示共享相同标签的其他项目。比如展示id为372的项目时,要显示id为584(共享space标签)和549(共享children标签)的关联项目。我能用循环实现,但想知道怎么用ES6语法实现?目前写的代码返回空数组:

我的错误代码

const items = [{
    id: 584,
    title: "spaceships",
    tags: ["space"],
  },
  {
    id: 372,
    title: "children's space",
    tags: ["children", "space"],
  },
  {
    id: 546,
    title: "teddy bears at the beach",
    tags: ["teddy bears", "beach"],
  },
  {
    id: 549,
    title: "children's toys",
    tags: ["children", "toys"],
  }
];

const tags = ["children", "space"]

const relatedItems = items.filter((item) => {
  return item.tags.some((n) => tags.includes(n))
});

console.log(relatedItems);
解决方法

你的代码逻辑本身没问题,但漏了排除当前项目自身的关键条件,另外可以优化成更通用的写法,不用硬编码标签数组:

完整ES6实现代码

const items = [
  { id: 584, title: "spaceships", tags: ["space"] },
  { id: 372, title: "children's space", tags: ["children", "space"] },
  { id: 546, title: "teddy bears at the beach", tags: ["teddy bears", "beach"] },
  { id: 549, title: "children's toys", tags: ["children", "toys"] }
];

// 定义要展示的目标项目ID
const targetId = 372;
// 先找到目标项目,获取它的标签集合
const targetItem = items.find(item => item.id === targetId);
const targetTags = targetItem.tags;

// 筛选关联项目:排除自身 + 有至少一个共同标签
const relatedItems = items.filter(item => {
  return item.id !== targetId && item.tags.some(tag => targetTags.includes(tag));
});

console.log(relatedItems);
// 输出结果:
// [
//   { id: 584, title: "spaceships", tags: ["space"] },
//   { id: 549, title: "children's toys", tags: ["children", "toys"] }
// ]

关键说明

  • 用find()快速定位目标项目,自动获取它的标签,不用手动写死标签数组
  • filter()过滤时,先通过item.id !== targetId排除当前展示的项目
  • 用some()+includes()组合判断:只要当前项的标签和目标项目有重叠,就算关联项目

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 09:57:28