用对象中的新值替换数组中的重复项

发布于 2025-02-11 09:21:09 字数 508 浏览 0 评论 0原文

我正在尝试“平坦”一个具有多个重复值的数组。该数组是由CSV创建的,然后我尝试运行API请求。 CSV的格式如下:

Posts | Comments | 
post1   comment1
post1   comment2
post1   comment3
post2   comment1
post2   comment2
post2   comment3

我使用的是返回的papaparse:

[{post:'post1',注释:'comment1'},{post:'post1',注释:'comment2'},。 。

​]

我尝试使用.map并引用索引检查是否与当前post相同>发布如果是.push到上一个索引,我无法使用.map .map进行

此操作的正确方法是什么?

I'm trying to "flatten" an array that has multiple duplicate values. The array is created from a CSV that I'm then trying to run API requests on.
The format of the CSV is as follows:

Posts | Comments | 
post1   comment1
post1   comment2
post1   comment3
post2   comment1
post2   comment2
post2   comment3

I'm using Papaparse which returns:

[{Post: 'post1', Comment: 'comment1'}, {Post: 'post1', Comment: 'comment2'}, ...]

So I thought I would try to flatten them to where it would look like:

[{Post: 'post1', {Comment: 'comment1'}, {Comment: 'comment2'}}]

I tried using a .map and referencing the index to check if the previous Post was the same as the current Post if it is then .push to the previous index which I can't do using .map

What would be the correct way of doing this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绝情姑娘 2025-02-18 09:21:09
  • 使用 ,在更新 地图 其中post是键,该值是一个具有post和分组注释 post的数组
  • 使用 映射#值 ,您可以获取分组对象的列表
const data = [ { Post: 'post1', Comment: 'comment1' }, { Post: 'post1', Comment: 'comment2' }, { Post: 'post1', Comment: 'comment3' }, { Post: 'post2', Comment: 'comment1' }, { Post: 'post2', Comment: 'comment2' }, { Post: 'post2', Comment: 'comment3' } ];

const res = [...
  data.reduce((map, { Post, Comment }) => {
    const { Comments = [] } = map.get(Post) ?? {};
    map.set(Post, { Post, Comments: [...Comments, Comment] });
    return map;
  }, new Map)
  .values()
];

console.log(res);

  • Using Array#reduce, iterate over the list while updating a Map where the Post is the key and the value is an object with Post and grouped Comments array for the Post
  • Using Map#values, you can get a list of grouped objects

const data = [ { Post: 'post1', Comment: 'comment1' }, { Post: 'post1', Comment: 'comment2' }, { Post: 'post1', Comment: 'comment3' }, { Post: 'post2', Comment: 'comment1' }, { Post: 'post2', Comment: 'comment2' }, { Post: 'post2', Comment: 'comment3' } ];

const res = [...
  data.reduce((map, { Post, Comment }) => {
    const { Comments = [] } = map.get(Post) ?? {};
    map.set(Post, { Post, Comments: [...Comments, Comment] });
    return map;
  }, new Map)
  .values()
];

console.log(res);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文