I have an array of objects consisting of items:
[
{
CATEGORY:"Fruits"
ITEM_AVAIL:true
ITEM_NAME:"Apple"
ITEM_PRICE:100
ITEM_UNIT:"per_kg"
ITEM_UPDATED:Object
ORDER_COUNT:0
},
{
CATEGORY:"Vegetables"
ITEM_AVAIL:true
ITEM_NAME:"Aloo"
ITEM_PRICE:1000
ITEM_UNIT:"per_kg"
ITEM_UPDATED:Object
ORDER_COUNT:0
}
]
I want create a new object such that each key of the object is a category and holds the array of objects of items, for example:
{
Fruits: [
{
CATEGORY:"Fruits"
ITEM_AVAIL:true
ITEM_NAME:"Apple"
ITEM_PRICE:100
ITEM_UNIT:"per_kg"
ITEM_UPDATED:Object
ORDER_COUNT:0
},
//more fruits
]
Vegetables: [
{
CATEGORY:"Vegetables"
ITEM_AVAIL:true
ITEM_NAME:"Aloo"
ITEM_PRICE:1000
ITEM_UNIT:"per_kg"
ITEM_UPDATED:Object
ORDER_COUNT:0
},
//more vegetables
]
}
the new object will be created based on category of item.
You can create new object like this
var data = [ { CATEGORY:"Fruits", ITEM_AVAIL:true, ITEM_NAME:"Apple", ITEM_PRICE:100, ITEM_UNIT:"per_kg", ITEM_UPDATED:Object, ORDER_COUNT:0, }, { CATEGORY:"Vegetables", ITEM_AVAIL:true, ITEM_NAME:"Aloo", ITEM_PRICE:1000, ITEM_UNIT:"per_kg", ITEM_UPDATED:Object, ORDER_COUNT:0, } ]; var newobj = []; for (i in data){ newobj[i] = []; newobj[i][data[i].CATEGORY] = data[i]; } console.log(newobj);
You can use a map to group elements by category as the key, and the list of items as the value:
let items = [ { CATEGORY:"Fruits", ITEM_AVAIL:true, ITEM_NAME:"Apple", ITEM_PRICE:100, ITEM_UNIT:"per_kg", ITEM_UPDATED:Object, ORDER_COUNT:0 }, { CATEGORY:"Vegetables", ITEM_AVAIL:true, ITEM_NAME:"Aloo", ITEM_PRICE:1000, ITEM_UNIT:"per_kg", ITEM_UPDATED:Object, ORDER_COUNT:0 }, { CATEGORY:"Fruits", ITEM_AVAIL:true, ITEM_NAME:"Apple1", ITEM_PRICE:200, ITEM_UNIT:"per_kg", ITEM_UPDATED:Object, ORDER_COUNT:0 }, { CATEGORY:"Vegetables", ITEM_AVAIL:true, ITEM_NAME:"Aloo1", ITEM_PRICE:2000, ITEM_UNIT:"per_kg", ITEM_UPDATED:Object, ORDER_COUNT:0 }, ] let obj = {}; items.forEach((item) => { if(!obj[item.CATEGORY]) obj[item.CATEGORY] = [ item ]; else obj[item.CATEGORY].push(item); }); console.log(obj);
Use Array#reduce . Look if for the actual object there exists a property with this category as name. If not so create it with an empty array as value. In both cases ass to this array the object.
let arr = [ { CATEGORY:"Fruits", ITEM_AVAIL:true, ITEM_NAME:"Apple", ITEM_PRICE:100, ITEM_UNIT:"per_kg", ITEM_UPDATED:Object, ORDER_COUNT:0, }, { CATEGORY:"Vegetables", ITEM_AVAIL:true, ITEM_NAME:"Aloo", ITEM_PRICE:1000, ITEM_UNIT:"per_kg", ITEM_UPDATED:Object, ORDER_COUNT:0, } ]; let res = arr.reduce((acc, cur) => { if (!acc[cur.CATEGORY]) { acc[cur.CATEGORY] = []; } acc[cur.CATEGORY].push(cur); return acc; },{}); console.log(res);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.