javascript - 在具有相同键的对象中获取乘键值
问题描述
JSON数据:
[{"name":"David","text":"Hi"},{"name":"Test_user","text":"test"},{"name":"David","text":"another text"}]
我想要循环搜索例如大卫的文本并在 HTML 中显示它:
<h1>Hi</h1>
<h1>another text</h1>
我很抱歉表达不好,但我不知道如何解释。
解决方案
这是一个经过测试的快速代码,可帮助我获取重复项,我正在打印它们,但您可以存储或返回它..
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);
}
});
推荐阅读
- git - 我什么时候应该使用“git push --force-if-includes”
- reactjs - 使用框架单元渲染器的 Ag 网格会在任何商店更改时不断重新渲染
- isabelle - 要求澄清伊莎贝尔理论中涉及自然数的理论中明显的实强制的出现
- batch-file - 如何在批处理脚本中找到我的错误?
- sql - Firebird 音译问题:从 utf8 客户端转换为 win1252 db 服务器
- mysql - 找出库存水平变为负数之前的天数
- sql-server - 本周间隔
- bazel - 将 copts/defines 传播到目标的所有依赖项
- c# - 在 ClickOnce 应用程序中包含字体文件
- python-3.x - Tkinter 给了我第二个窗口