Generate a novel item by organizing the key of an array of objects

I have an array of objects containing various 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 am looking to create a new object where each key corresponds to a category, holding the array of item objects within that category. For instance:

{
  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
    ]
}

This new object will be organized based on the category of each item.

Answer №1

If you want to create a new object, follow this example

var items = [
      {
        CATEGORY:"Electronics",
        ITEM_AVAIL:true,
        ITEM_NAME:"Laptop",
        ITEM_PRICE:1200,
        ITEM_UNIT:"each",
        ITEM_UPDATED:Object,
        ORDER_COUNT:0,

      },
      {
        CATEGORY:"Clothing",
        ITEM_AVAIL:true,
        ITEM_NAME:"Shirt",
        ITEM_PRICE:30,
        ITEM_UNIT:"each",
        ITEM_UPDATED:Object,
        ORDER_COUNT:0,

      }
   ];
var newObj = [];
for (index in items){        
    newObj[index] = [];
    newObj[index][items[index].CATEGORY] = items[index];
}       
console.log(newObj);

Answer №2

You have the option to utilize a map for grouping elements based on their category as the key, with the list of items serving as the corresponding value:

let products = [
  {
    CATEGORY:"Electronics",
    ITEM_AVAIL:true,
    ITEM_NAME:"Laptop",
    ITEM_PRICE:1000,
    ITEM_UNIT:"per_piece",
    ITEM_UPDATED:Object,
    ORDER_COUNT:0
  },
  {
    CATEGORY:"Clothing",
    ITEM_AVAIL:true,
    ITEM_NAME:"T-shirt",
    ITEM_PRICE:20,
    ITEM_UNIT:"per_piece",
    ITEM_UPDATED:Object,
    ORDER_COUNT:0
  },
  {
    CATEGORY:"Electronics",
    ITEM_AVAIL:true,
    ITEM_NAME:"Headphones",
    ITEM_PRICE:50,
    ITEM_UNIT:"per_pair",
    ITEM_UPDATED:Object,
    ORDER_COUNT:0
  },
]
let categories = {};
products.forEach((product) => {
     if(!categories[product.CATEGORY])
          categories[product.CATEGORY] = [ product ];
     else
          categories[product.CATEGORY].push(product);
});
console.log(categories);

Answer №3

Utilize Array#reduce method to organize objects based on their category property. If a category property does not exist, create it with an empty array as its initial value and add the object to it.

let products = [
  {
    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 result = products.reduce((acc, current) => {
    if (!acc[current.CATEGORY]) {
        acc[current.CATEGORY] = [];
    }
    acc[current.CATEGORY].push(current);
    return acc;
},{});

console.log(result);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Suggestions for placing a script under the scripts menu in Illustrator CS5.1

My script for Adobe Illustrator CS5.1 is not showing up in the scripts menu despite trying to place it in various directories such as: C:\Program Files\Adobe\Adobe Illustrator CS5.1\Presets\en_GB\Scripts\ C:\Progra ...

Modify Knockout applyBindings to interpret select choices as numeric values

Utilizing Knockout alongside html select / option (check out Fiddle): <select data-bind="value: Width"> <option>10</option> <option>100</option> </select> Upon invoking applyBindings, the options are interprete ...

Is it possible for you to execute 2 procedures consecutively simply by clicking on a button?

My question is quite straightforward. I have two buttons: <button @click="getPartyLeader" class="btn btn-success">Get party leader</button> <button @click="saveParty" class="btn btn-success">Submi ...

Using PHP variables in JavaScript to access getElementById

I have multiple forms displayed on a single PHP page. They all follow a similar structure: <form id="test_form_1" action="test_submit.php" method="post" name="test_form"> <label>This is Question #1:</label> <p> &l ...

If I dared to eliminate the emphasized line, this code would completely fall apart

<!DOCTYPE html> <html> <head> </head> <body> <h1 id="message-el">Ready to play?</h1> <p id="cards-el"></p> <p id="sum-el"></p> <butto ...

Comprehending the significance of *this* within class structures

I've got this code snippet below. class Node { constructor(value, parent, possibleChildren = []) { this.value = value; this.parent = parent; this.children = [] this.setChildren(possibleChildren); } setChildren(possibleChil ...

How can I customize button colors in react-bootstrap components?

Changing colors in react-bootstrap may be a challenge, but I'm looking to customize the color of my button beyond the primary options. Any suggestions on how I can achieve this using JS and SCSS? ...

Upon initial page load, React JS is unable to fetch the data but it functions correctly when triggered by a click

Here is the code I am working with: var CommonHeader = require('./header/CommonHeader.jsx'); var ListOptions = require('./header/ListOptions.jsx'); var SortableTable = require('../shared/SortableTable.jsx'); var ColumnDefinit ...

Selecting random subarrays from a two-dimensional array in Python

Issue: Imagine I have a 2D array and I am looking to randomly extract smaller sub-arrays using the Monte-Carlo method, similar to the black patches in the figure provided below. I need an efficient way to execute this process. https://i.sstatic.net/Zx7X7 ...

The schema validation test in POSTMAN results in a failure

Below is an example response that I have provided: { "tags": [ { "id": 1, "name": "[String]", "user_id": 1, "created_at": "2016-12-20T15:50:37.000Z", "updated_at": "2016-12-20T15:50:37.000Z", "deleted_at": null ...

Accessing API using Next.js 14

I am facing an issue with the following code which is written in next.js. The error displayed on the console is: GET http://localhost:3000/products/porducts.json 404 (not found) Additionally, I'm encountering this error: Uncaught (in promise) SyntaxE ...

Troubleshooting issue with refreshing selectpicker in Bootstrap-select and Vue.js

Incorporating the bootstrap-select plugin (found at ) into a ruby on rails app with Vue.js as the javascript framework has been my latest project. The goal is to have two select options where one selects a category and the other displays all available tea ...

Conceal a Component within an Embedded Frame

Hey there! I've been attempting to hide a header within an iframe, but it seems like my code isn't doing the trick. Could someone take a look and help me diagnose why the header is still visible? Thanks in advance! <iframe id="booking_iframe" ...

Having trouble getting webpack and babel to start using npm

Greetings, wonderful people of the internet! I am a newcomer to the enchanting world of programming and I am facing a perplexing issue. Although Webpack is trying to guide me towards the solution, I seem to be struggling with fixing it on my own. const pa ...

Navigating through the Jquery DOM to access a specific node

Displayed here are a list of products, presented within an unordered list: Users can express interest in specific items by clicking "I am Interested," prompting a change in background color and the appearance of a tick mark next to the selected item. To ...

Navigating the screen reader with the cursor位

Site Design Challenge I recently discovered that the master/detail design of my website is not very accessible. The main view features a column chart where each column represents a different month. Clicking on one of these columns reveals details in a nes ...

Having trouble setting the focus on a text box following a custom popup

Presenting a stylish message box and attempting to focus on a textbox afterward, however, it's not functioning as expected. Below is the HTML code: <a class="fancyTrigger" href="#TheFancybox"></a> <hr> <div id="TheFancybox">& ...

Programming in C: Creating Text Files with Random Numbers, Analyzing Occurrences, and Conducting Statistical Analysis

I am working on a program that generates random numbers and saves them to a new text file. The goal is to then analyze the generated values, counting how many times each number appears in the file (e.g. Number 1 has appeared "x" number of times). I expect ...

React Application Issue 'Error: React is not defined'

I've been working on developing an app using react, but for some reason, it's not functioning properly and I'm struggling to pinpoint the issue. The code compiles without errors using babelify, however, it throws an exception during executio ...

A quick guide on automatically populating text boxes with characteristics of the item chosen from a drop-down menu

On my webpage, I am looking to automatically populate textboxes with information (such as common name, location, etc.) of the selected shop from a dropdown list without having to refresh the page. Here is the dropdown list: <select id="shops" class="f ...