Home > Back-end >  organizes items by category
organizes items by category

Time:09-23

I have to write a function, organizeItems, that organizes items by category. The argument to the function is an array of item objects. Each item object has 3 properties, category (string), itemName (string), and onSale (Boolean).

var itemData = [
  { category: 'fruit', itemName: 'apple', onSale: false },
  { category: 'canned', itemName: 'beans', onSale: false },
  { category: 'canned', itemName: 'corn', onSale: true },
  { category: 'frozen', itemName: 'pizza', onSale: false },
  { category: 'fruit', itemName: 'melon', onSale: true },
  { category: 'canned', itemName: 'soup', onSale: false },
];

The return value should be an object with category properties. Each property value is an array of items that belong to that category and having onSale set to true should have '($)' appended to their item name. This is an example of what I'm trying to do:

{
  fruit:  ['apple', 'melon($)'],
  canned: ['beans', 'corn($)', 'soup'],
  frozen: ['pizza']
};

So far this is what I have:

var obj = {};
for (var i = 0; i < itemData.length; i  )
   console.log(itemData[i]);

But I don't know how to iterate through each object to get what I need.

CodePudding user response:

Hello I did it like so.

     const obj = {};
    itemData.map((item, index) => {
      let objKeys = Object.keys(item);
      objKeys.forEach((k) => {
        if (k === "category") {
          if (!obj[item[k]]) {
            obj[item[k]] = [];
          }

          if (!obj[item[k]].find((i) => i === item.itemName)) {
            obj[item[k]].push(
              item.onSale ? `${item.itemName}($)` : item.itemName
            );
          }
        }
      });
    });
    console.log("obj", obj);

CodePudding user response:

my way

const itemData = 
  [ { category: 'fruit',  itemName: 'apple', onSale: false } 
  , { category: 'canned', itemName: 'beans', onSale: false } 
  , { category: 'canned', itemName: 'corn',  onSale: true  } 
  , { category: 'frozen', itemName: 'pizza', onSale: false } 
  , { category: 'fruit',  itemName: 'melon', onSale: true  } 
  , { category: 'canned', itemName: 'soup',  onSale: false } 
  ] 

const result = itemData.reduce((r,{category,itemName,onSale})=>
  {
  r[category] = r[category] || []
  r[category].push( itemName   (onSale?'($)':''))
  return r
  },{})
 
// show result
console.log( JSON.stringify(result)
                 .replace(`{"`,`\nresult =\n  { `)
                 .replace(/"],"/g,`' ]\n  , `)
                 .replace(`"]}`,`' ]\n  }`)
                 .replace(/":\["/g,`: [ '`)
                 .replace(/","/g,`', '`))
.as-console-wrapper {max-height: 100%!important;top:0 }

  • Related