简体   繁体   English

如何基于香草javascript中的属性对对象数组进行分组

[英]How to groupBy array of objects based on properties in vanilla javascript

How do you groupBy array of objects based on specific properties in vanilla javascript? 如何基于香草javascript中的特定属性对对象数组进行分组 For example this given: 例如,给出:

const products = [
  {
    category: "Sporting Goods",
    price: "$49.99",
    stocked: true,
    name: "Football"
  },
  {
    category: "Sporting Goods",
    price: "$9.99",
    stocked: true,
    name: "Baseball"
  },
  {
    category: "Sporting Goods",
    price: "$29.99",
    stocked: false,
    name: "Basketball"
  },
  {
    category: "Electronics",
    price: "$99.99",
    stocked: true,
    name: "iPod Touch"
  },
  {
    category: "Electronics",
    price: "$399.99",
    stocked: false,
    name: "iPhone 5"
  },
  { category: "Electronics", price: "$199.99", stocked: true, name: "Nexus 7" }
];

i want to run a reduce function that would result to a new array of objects like this: 我想运行一个reduce函数,该函数会导致像这样的对象新数组:

Intended Output: 预期输出:

const categorize = [
  {
    category:"Sporting Goods",
    products: [
      {
        name:"Football",
        price: "$49.99",
        stocked: true
      },
      {
        name:"Baseball",
        price: "$9.99",
        stocked: true
      },
      {
        name:"Basketball",
        price: "$29.99",
        stocked: true
      }
    ]
  },
  {
    category: "Electronics",
    products: [
      {
        name: "iPod Touch",
        price: "$99.99",
        stocked: true
      },
      {
        name: "iPhone 5",
        price: "$399.99",
        stocked: false
      },
      {
        name: "Nexus 7",
        price: "$199.99",
        stocked: true
      }
    ]
  }
]

i based my solution from the tutorial here: https://www.consolelog.io/group-by-in-javascript/ using the reduce function. 我使用以下功能基于本教程中的解决方案: https//www.consolelog.io/group-by-in-javascript/

Here's my code: 这是我的代码:

const groupBy = (arr,prop)=>{
  return arr.reduce((groups,item)=>{
    let val = item[prop];
    groups[val] = groups[val]||[];
    groups[val].push(item);
    return groups
  },{});
}

const categorize = groupBy(products,'category');
console.log(categorize);

/* returns an Object like
    Object {Sporting Goods: Array[3], Electronics: Array[3]}
   however it's not the intended output.
*/

I tried to return Object.values(obj) or Object.entries(obj) inside the groupBy function but it just returns an array of 2 arrays like [Array[3],Array[3]] and if i set the initial value (2nd parameter of reduce) to empty [] instead of {}, the output is just an empty array. 我试图在groupBy函数内部返回Object.values(obj)Object.entries(obj) ,但它只返回2个数组的数组,例如[Array[3],Array[3]] ,如果我设置了初始值(减少的第二个参数)为空[]而不是{},输出只是一个空数组。 Need help, thanks! 需要帮助,谢谢!

Because you want an array containing objects (rather than just an array of plain values), create a { category, products: [] } object if it doesn't exist in the accumulator: 因为您想要一个包含对象的数组(而不仅仅是纯值的数组),所以创建一个{ category, products: [] }对象(如果该对象在累加器中不存在):

 const products=[{category:"Sporting Goods",price:"$49.99",stocked:!0,name:"Football"},{category:"Sporting Goods",price:"$9.99",stocked:!0,name:"Baseball"},{category:"Sporting Goods",price:"$29.99",stocked:!1,name:"Basketball"},{category:"Electronics",price:"$99.99",stocked:!0,name:"iPod Touch"},{category:"Electronics",price:"$399.99",stocked:!1,name:"iPhone 5"},{category:"Electronics",price:"$199.99",stocked:!0,name:"Nexus 7"}]; const output = Object.values( products.reduce((a, { category, ...item }) => { if (!a[category]) { a[category] = { category, products: [] }; } a[category].products.push(item); return a; }, {}) ); console.log(output); 

    function (){
var map = {};
products.forEach((p) => {
  if (map[p.category]) {
 var c = p.category;
delete p.category;
  map[c].push(p);
} else {
 var c = p.category;
delete p.category;
map[c]=[c]
}
});

Object.keys(map).forEach((m) => {
ans.push({category:m, products: map[m]})
})

} }

you can collect in one go products and map them. 您可以一次性收集产品并绘制地图。 Then make your resultinng array 然后使您的resultinng数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM