【问题标题】:Get multiply key'value in object that have the same key获取对象中具有相同键的多个键值
【发布时间】:2021-03-31 11:54:31
【问题描述】:

JSON 数据:

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

我想要循环搜索例如David 的文本并以 HTML 格式显示:

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

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

【问题讨论】:

  • 您可以按“名称”分组,然后获取对象的值
  • 迭代和积累。展示你的尝试

标签: javascript node.js arrays json object


【解决方案1】:

HTML 内容

<div class="wrapper">

</div>

JS 内容

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

const searchKey = 'David';

// filter the objects with name "David" or "david"
const searchResult = list.filter(({ name }) => name.toLowerCase() === searchKey.toLowerCase());

// render the filtered array on HTML
const parentWrapper = document.querySelector('.wrapper');
searchResult.forEach((el) => {
    const child = document.createElement('h1');
    child.textContent = el.text;
    parentWrapper.appendChild(child);
});

【讨论】:

    【解决方案2】:

    这是一个经过测试的快速代码,可帮助我获取副本,我正在打印它们,但您可以将其存储或退回..

    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);
      }
    });
    

    【讨论】:

      【解决方案3】:

      我认为你想要的是这样的:

      const myArray = [{"name":"David","text":"Hi"},{"name":"Test_user","text":"test"},{"name":"David","text":"another text"}]
      
      const davidData = myArray.find(i => i.name === "David") // = {"name":"David","text":"Hi"}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-18
        • 1970-01-01
        • 1970-01-01
        • 2020-11-25
        • 1970-01-01
        • 2011-08-27
        • 1970-01-01
        相关资源
        最近更新 更多