Operating with JavaScript arrays and objects

My JavaScript array/object consists of the following data:

[
  {
    "name": "A",
    "selected_color": "Red"
  },
  {
    "name": "B",
    "selected_color": "Green"
  },
  {
    "name": "C",
    "selected_color": "Blue"
  },
  {
    "name": "D",
    "selected_color": "Red"
  }
]

What steps should I take to transform it into the desired format below?

[
  {
    "color": "Red",
    "count": "2"
  },
  {
    "color": "Green",
    "count": "1"
  },
  {
    "color": "Blue",
    "count": "1"
  }
]

I aim to filter values based on the 'selected_color' key and keep track of how many times each specific color was selected.

Answer №1

Optimize with .reduce method

const data = [
  {
    "name": "X",
    "color_selected": "Yellow"
  },
  {
    "name": "Y",
    "color_selected": "Blue"
  },
  {
    "name": "Z",
    "color_selected": "Yellow"
  }
];

const result = data.reduce((acc, current) => {
  const {color_selected} = current;
  const colorObject = acc.find(({color}) => color === color_selected );

  if(colorObject) {
    colorObject.quantity++;
  } else {
    acc.push({color: color_selected, quantity: 1});
  }

  return acc;
  
}, []);

console.log(result);
/*

[
  { color: 'Yellow', quantity: 2 },
  { color: 'Blue', quantity: 1 }
]

*/

Answer №2

If you want to organize the data by color, you can achieve this using the groupBy function like so:

let items = [
{
    "name": "X",
    "selected_color": "Orange"
},
{
    "name": "Y",
    "selected_color": "Yellow"
},
{
    "name": "Z",
    "selected_color": "Red"
},
{
    "name": "W",
    "selected_color": "Orange"
}
];

let groupByColor = (arr, key) => {
    return arr.reduce((result, item) => {
        (result[item[key]] = result[item[key]] || []).push(item);
        return result;
    }, {});
};

let groupedItems = groupByColor(items, "selected_color");
let organizedData = Object.keys(groupedItems).map(color => ({'color': color, 'count': groupedItems[color].length}) );

console.log(organizedData);

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

Proper method for validating Jwt

Below is the code I have composed: jwt.verify(token.split(':')[1], 'testTest') I am attempting to verify this code in order for it to return true and proceed. The jwt being mentioned here serves as an example payload. Any suggestions ...

The AJAX call for fetching logged in users is coming back as undefined

Hey there! I'm currently diving into the world of AJAX and am working on enhancing the user experience on my admin system. One thing I want to achieve is to update information like online users, messages, tasks, etc. every 30 seconds or so (for testin ...

I'm puzzled as to why a div tag suddenly becomes invisible when I attempt to link it with a v-for directive in my code

I am facing an issue with the div tag assigned to the log class. My objective is to populate the text using data retrieved from the API response. However, when I attempt to include the v-for directive, the entire div mysteriously disappears from the brow ...

Refreshing a Node.js server page upon receiving a JSON update

My web application serves as a monitoring interface for tracking changes in "objects" processed by the computer, specifically when they exceed a certain threshold. The Node Js server is running on the same machine and is responsible for displaying data in ...

Unspecified OrbitControls Compatibility Issue between Angular2 and Three.js

I'm running into issues trying to set up OrbitControls in my Angular2 project. I managed to display a scene with a box, but I'm struggling to move the camera. Upon investigation, I found that my OrbitComponent, responsible for defining orbit con ...

Looking to prevent printing and saving a webpage directly from the file menu using JQUERY or JavaScript

I am in need of assistance to find a code that can disable the ability to print and save a webpage using JQUERY or JAVASCRIPT ...

Remove the active class from a list item using History.js

My goal is to add the active class to a link when clicked in my AJAX app, triggering statechange on History.js. I'm struggling with saving the current active link(s) with the state so that the active class is appropriately added or removed when naviga ...

What is the process for integrating Socket io into an external JavaScript file that is connected to an HTML file?

Currently, I am utilizing node js, socket io, and express to develop a multiplayer web game. To begin, the server initiates and listens on port 2000. Upon visiting localhost:2000, the file lobby.html is transmitted using: //app.js const express = require ...

Issue encountered while constructing my application (utilizing the "yarn run build" command and in Vercel)

Encountered an error during the build process, whether on the server or locally. This issue arises when using package managers like yarn, npm, and others. The error specifically points to a problem in the CSS file, but it only occurs in the production bu ...

Unusual HTML Structure (content misplaced or out of order?)

Recently, I started learning CSS/HTML in school and we just delved into Javascript. Currently, we are working on a website project. However, while trying to integrate the content with the navbar, I encountered a strange issue. When resizing to 620px or le ...

Retrieving objects from JSON data

I'm facing a challenge in creating a React component that showcases test results from various courses. The issue lies in accessing the scores object within the provided JSON file. Here is an excerpt from the JSON data I am currently working on: [ ...

How to hide an image in the React carousel display

I am having an issue with my Carousel, specifically with the image not being displayed even though I have set up the data in a const called items. Here is how my const looks: var items = [ { url:'../../assets/img/hors1.jpg', ...

A program that saves numerous data from a JSON dictionary into an array

I have a large collection of dictionaries in JSON format obtained through an API request totaling over 1000. How can I develop a script that can loop through all the dictionaries and extract the values from one specific key-value pair? For instance: "te ...

What is the best way to transform an array of objects into MenuItems for a Material-UI Select component?

I am facing an issue with mapping the values of field choices to create options for an MUI Select field from an array called fieldChoices. Here is how I populate the fieldChoices array: fieldChoices = { choices: filtered_status.map(function (item) { ...

Error parsing data in the $.ajaxSetup() function of JQuery

Currently, I am coding a program using jQuery. It was functioning perfectly in Firefox 3.5 until I upgraded to Firefox 4.0. Since then, the dreaded 'parsererror' keeps popping up and causing me quite a headache. I've pinpointed the exact pa ...

Tips for utilizing JavaScript functions within Vue directives?

Let's say I have a JS function that looks like this: function myFunc() { return true; } Now, I want to display an element if the output of the function is true: <p v-if="myFun()">I am Test</p> I understand that I can place the myFun ...

Convert JSON data into an HTML table with custom styling

If you have a set of JSON data that you want to convert into an HTML table, you can use the following code: $.each(data, function(key, val) { var tr=$('<tr></tr>'); $.each(val, function(k, v){ $('<td>' ...

I am having trouble adding multiple items on different occasions - is it something to do with JQUERY

I have been working on a dynamic website that loads Firebase values into a table. However, I encountered an issue where the data does not appear when going back to the orders page after visiting another page. After some testing, I found that placing a but ...

The Quivering Quandaries of Implementing Jquery Accordions

For a demonstration of the issue, please visit http://jsbin.com/omuqo. Upon opening a panel by clicking on the handle, there is a slight jitter in the panels below during the animation. In the provided demo, all panels should remain completely still as t ...