【问题标题】:How can I save data in different arrays depending on specific characteristics?如何根据特定特征将数据保存在不同的数组中?
【发布时间】:2021-11-09 19:29:44
【问题描述】:

我有一个包含超过 50 个对象形式的条目的数组,我想根据项目 ID 保存这些条目,以便我可以对它们应用某些计算。例如,我想将所有条目 ID 为“Las5241Wz”的条目的时间相加。


由于数组可以动态变化,我无法手动分析。如何根据项目 ID 预先分离数据并将它们推送到新数组中?真正的 Array 最多包含 16 个具有相同 ID 的对象。

var data= []
data = [
  //...objects
{
    itemId: "Las5241Wz", 
    time: 10
  },
  {
    itemId:"Bos1239Zf", 
    time: 11
  },
  {
    itemId:"Las5241Wz", 
    time: 15
  },
  {
    itemId:"Bos1239Zf", 
    time: 21
  }
//...more objets
   ]

解决方案应如下所示:

var Item1 = [
{
    itemId: "Las5241Wz", 
    time: 10
  },
{
    itemId:"Las5241Wz", 
    time: 15
  },
]

var Item2 = [
{
    itemId:"Bos1239Zf", 
    time: 11
  },
{
    itemId:"Bos1239Zf", 
    time: 21
  }
]

【问题讨论】:

  • 这能回答你的问题吗? How to group by and sum an array of objects?
  • @jarmod 因为我必须在总和之上使用多个计算,所以将单个对象存储在新数组中的解决方案会更好。我编辑了问题

标签: javascript arrays object


【解决方案1】:

这是另一种解决方案,它从给定对象构建具有“item1”、“item2”等属性的对象:

const data = [
  //...objects
{
itemId: "Las5241Wz", 
time: 10
  },
  {
itemId:"Bos1239Zf", 
time: 11
  },
  {
itemId:"Las5241Wz", 
time: 15
  },
  {
itemId:"Bos1239Zf", 
time: 21
  }
//...more objets
   ]

console.log(
Object.values(
data.reduce((o,e)=>((o[e.itemId]=o[e.itemId]||[]).push(e),o),{}))
.reduce((o,c,i)=>(o["item"+(i+1)]=c,o),{})
);

这是一个“单行”,因此不那么容易阅读。因此,可能不是您要放入生产代码的版本。

【讨论】:

    【解决方案2】:

    除非您出于性能原因将列表分开保存,否则答案是您可以将 id 列表存储为 Set 并在您想要获取仅用于该 id 的列表时使用 array.filter

    Set s = new Set();
    for (let i = 0; i < data.length; i++) {
      s.add(data[i].itemId);
    }
    
    var createFilterFunc(id) {
      return function(elem) {
        return elem.itemId == id;
      }
    }
    
    var items = data.filter (createFilterFunc("Las5241Wz"));
    

    【讨论】:

      猜你喜欢
      • 2021-03-28
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      • 1970-01-01
      • 2014-07-31
      • 2016-04-07
      • 2017-04-12
      • 1970-01-01
      相关资源
      最近更新 更多