【问题标题】:sort the objects in array that has same value to one object inside the same array将数组中与同一数组中的一个对象具有相同值的对象排序
【发布时间】:2021-02-15 13:52:23
【问题描述】:

我正在发出返回对象数组的 Fetch 请求,如下所示:

[
   {"id":11,"name":"test1","day":"MON","level":2},
   {"id":13,"name":"test2","day":"TUE","level":3},
   {"id":14,"name":"test1","day":"WED","level":4},
   {"id":15,"name":"test2","day":"FRI","level":5}
]

所以,在这个数组里面我有四个对象,每两个都有相同的名字,所以我希望结果是这样的:

 {
           "test1" : [
                       {"id":11,"name":"test1","day":"MON","level":2}, 
                       {"id":14,"name":"test1","day":"WED","level":4}
                    ],
           "test2" :[
                      {"id":13,"name":"test2","day":"TUE","level":3}, 
                      {"id":15,"name":"test2","day":"FRI","level":5}
                    ]
  }

【问题讨论】:

  • 现在说得通了。你要找的是groupby。遗憾的是 JS 没有为此提供内置方法,因为这是一项常见的任务,但是如果您在 SO 上搜索它,您会发现大约一百万个结果/答案

标签: javascript arrays json javascript-objects


【解决方案1】:

你可以使用reduce函数

const arr = [
   {"id":11,"name":"test1","day":"MON","level":2},
   {"id":13,"name":"test2","day":"TUE","level":3},
   {"id":14,"name":"test1","day":"WED","level":4},
   {"id":15,"name":"test2","day":"FRI","level":5}
];

const result = arr.reduce((acc, cur) => {
    acc[cur.name] = acc[cur.name] || [];
  acc[cur.name].push(cur);
  return acc;
}, {})

console.log(result);
console.log(Object.values(result).flat());

【讨论】:

  • 我注意到 result 它打印为对象如何使其成为数组
  • 在你的问题中,你提到你想要一个对象。我说的对吗?
  • 是的,先生,您是对的,但如果您不介意如何做到这一点,我将不胜感激。谢谢
  • 数组会是什么样子?我认为对象(如您所料)更有意义
  • 对此我很抱歉,这有点令人困惑,我想到了数组,因为我想打印我从你的答案test1 and test2 中得到的结果的值 FlatList in react native ,但我不确定是否有其他方法可以做到这一点。谢谢
猜你喜欢
  • 2022-06-10
  • 2021-04-09
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 2020-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多