代码之家  ›  专栏  ›  技术社区  ›  Datacrawler

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

  •  3
  • Datacrawler  · 技术社区  · 6 年前

    我有一个对象数组(dictionary是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 回复  |  直到 6 年前
        1
  •  2
  •   Nenad Vracar    6 年前

    reduce 方法,首先按库存进行分组,然后按目标进行分组。要返回数组数组作为结果,可以使用 Object.values map .

    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)