首页 > 解决方案 > 在具有相同键的对象中获取乘键值

问题描述

JSON数据:

[{"name":"David","text":"Hi"},{"name":"Test_user","text":"test"},{"name":"David","text":"another text"}]

我想要循环搜索例如大卫的文本并在 HTML 中显示它:

<h1>Hi</h1>
<h1>another text</h1>

我很抱歉表达不好,但我不知道如何解释。

标签: javascriptnode.jsarraysjsonobject

解决方案


这是一个经过测试的快速代码,可帮助我获取重复项,我正在打印它们,但您可以存储或返回它..

arr = [
  { name: "David", text: "Hi" },
  { name: "Test_user", text: "test" },
  { name: "David", text: "another text" },
];

const groupBy = (arrayInput, key) => {
  return arrayInput.reduce(
    (r, v, i, a, k = v[key]) => ((r[k] || (r[k] = [])).push(v), r),
    {}
  );
};

groupedByName = groupBy(arr, "name");

ans = Object.entries(groupedByName).map(([key, value]) => {
  if (value.length > 1) {
    // here is the list of duplicate for name: key
    const duplicates = value.map((item) => item.text);
    console.log(`name ${key} has duplicates: `, duplicates);
  }
});

推荐阅读