根据对象值创建子数组(两个对象分别有两个分组)

3
我有一个对象数组(在Python中称为字典,但在这种情况下我使用Javascript)。我的目标是将不同的对象分组。我的第一次尝试是基于库存值创建两个数组。然后对于每个数组,我想基于目标值创建三个不同的数组。
我认为我失去了逻辑,因为第二个分组(目标)不起作用。

var inventory = [
    {ID: "K111", Objective: "One", Inventory: "Second" },
    {ID: "K112", Objective: "Two", Inventory: "Second" },
    {ID: "K113", Objective: "One", Inventory: "Second" },
    {ID: "K114", Objective: "Three", Inventory: "Second" },    
    {ID: "K132", Objective: "One", Inventory: "First" }
];

var OBJECTIVE = ["One", "Two", "Three"];
var INVENTORY = ["Second", "First"];

//Create arrays per Inventory (2 possible values)
for (var i = 0; i < INVENTORY.length; i++) {
 
  var variable = inventory.filter(function(el) {
      return el.Inventory == INVENTORY[i];
  });
  
  window['arr'+i] = variable;
  document.getElementById("arr"+i).innerHTML =JSON.stringify(variable);

}

//Create arrays per Objective for each array created above
for (var i = 0; i < OBJECTIVE.length; i++) {

  j = i + 2;
  var variable = arr0.filter(function(el) {
      return el.Objective == OBJECTIVE[i];
  });
  
  window['arr'+j] = JSON.stringify(variable);
  document.getElementById("arr"+j).innerHTML =JSON.stringify(variable);

}


for (var i = 0; i < OBJECTIVE.length; i++) {

  var variable = arr1.filter(function(el) {
      return el.Objective == OBJECTIVE[i];
  });
  
  window['arr'+j] = JSON.stringify(variable);
  document.getElementById("arr"+j).innerHTML =JSON.stringify(variable);

}
<div style="background:yellow;" id="arr0"></div>
<div style="background:green;" id="arr1"></div>
<div style="background:grey;" id="arr2"></div>
<div style="background:blue; color:white;" id="arr3"></div>
<div style="background:red; color:white;" id="arr4"></div>
<div style="background:black; color:white;" id="arr5"></div>
<div style="background:orange;" id="arr6"></div>

 

1个回答

2

您可以使用reduce方法返回一个对象,首先按库存分组,然后按目标分组。要返回数组的数组作为结果,您可以使用Object.valuesmap

var data = [{ID: "K111", Objective: "One", Inventory: "Second" },{ID: "K112", Objective: "Two", Inventory: "Second" },{ID: "K113", Objective: "One", Inventory: "Second" },{ID: "K114", Objective: "Three", Inventory: "Second" },    {ID: "K132", Objective: "One", Inventory: "First" }];

var res = data.reduce((r, e) => {
  let {Objective, Inventory} = e;
  r[Inventory] = r[Inventory] || {}
  r[Inventory][Objective] = r[Inventory][Objective] || {}
  Object.assign(r[Inventory][Objective], e);
  return r;
}, {})

var array = Object.values(res).map(Object.values)

console.log(array)
console.log(res)


@Nenan Vracar 不错。有一个观察结果。K111缺失了,因为我猜测有重复的吧? - Datacrawler
@Apolo Radomer 是的。 - Nenad Vracar
有没有一种方法可以修改代码并使其正常工作?我不认为有。也许可以使用另一个函数,而不是reduce。这样对吗? - Datacrawler
是的。我可能会提出另一个问题。我正在尝试进行实验。因此,根据不同的情况,我将使用body构建(innerHTML)表格。根据上述查询中不存在的第三个对象,它将显示/隐藏其他对象(数字)。所以。我可能还需要聚合数据。 - Datacrawler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接