Determine the frequency of keys and transform the data into an array of objects, with each object corresponding to a key and its frequency

Illustration of Frequency Count

[
    { language: 'JavaScript' },{ language: 'JavaScript' },{ language: 'TypeScript' },
] 

CONVERSION TO =

[
{ language: 'JavaScript', count: 2 },
{ language: 'C++', count: 1 },
{ language: 'TypeScript', count: 1 }
]

The concept is to tally the occurrences of each unique key in an array of objects and then present the result as an array of objects. This format enables seamless rendering in frameworks like React.JS.

[ { key1: 2 }, { key2: 1 }, { key3: 7 } ]

Answer №1

Utilize the following code snippet to achieve your desired outcome. This code is applicable to all input scenarios where you need to provide an array along with the property name used for count calculation.

const superAob = (data, victim) => {

    const obj = {};
  
    data.forEach((data) => {
        if(data.hasOwnProperty(victim)){
            if(obj[data[victim]]){
                obj[data[victim]]++;
            }
            else{
                obj[data[victim]] = 1;
            }
        }
    })
  
    let superArrayOfObjects = [];
  
    for (const key in obj) {
        superArrayOfObjects = [...superArrayOfObjects, { victim: key, count: obj[key]}];
    }
  
    return superArrayOfObjects;
}

let aob = 
[
    { framework: 'React.JS', website: 'Paypal' },
    { framework: 'React.JS', website: 'Tesla' },
    { framework: 'Angular', website: 'Google' },
    { framework: 'Vue.JS', website: 'Vue' },
    { framework: 'JavaScript', website: 'inblack67' },
]

console.log(superAob(aob, 'framework'));

aob = 
[
    { language: 'JavaScript' },{ language: 'JavaScript' },{ language: 'TypeScript' },
]

console.log(superAob(aob, 'language'));

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

Problem with Vue.js dropdown functionality in Internet Explorer

After developing a form using Vue.js to allow users to save and return to their answers, I encountered an issue in Internet Explorer. When the page loads, the dropdown menu tied to a computed property does not display the previously selected answer as expe ...

Troubleshooting a JS promise issue with Kriskowal's Q library

I have been working with the kriskowal/q module to create a promise, but I am encountering an issue where it does not enter any function paths - neither the happy path nor the error path. Below is the class where I create the promise: var Q = require(&ap ...

What is the method for determining if a point lies between two others?

I created a small function that seems to have a glitch... function determineIfPointIsBetweenTwoOtherPoints (pointA, pointB, pointToCheck) { var vectorAB = new THREE.Vector3(); vectorAB.subVectors(pointA, pointB).normalize(); var vectorBA = ne ...

JS Data error: The attributes provided must include the property indicated by idAttribute - particularly with regards to hasMany relationships

Encountered Error: The main key for my user model is username. The primary key for my routes is the routename. When my API returns JSONs, they are nested inside data:{} following jsonapi.org specifications. However, this structure differs from what js-dat ...

Assistance needed with dynamically resizing a background image

Is there a way to automatically adjust the size of a background image for an element? For instance, I want my links in HTML to have a background image with slanted borders and rounded corners. Usually, you would set the width of the anchor element to fit t ...

Initiating iOS UIWebView when the DOM is fully loaded

One issue I'm facing is that UIWebView triggers webViewDidFinishLoad before its content is actually rendered, resulting in a short delay after the view is displayed before the content appears. I'm curious if there's a way to trigger an event ...

What is the correct way to access the text of a selected radio button within a datalist

Within the dataset below, there is a collection of questions and answers. How can you use JavaScript to verify if the user has selected the correct answer radio button before clicking the submit button? The answers are stored in a database. Data List: & ...

Load content in three.js using JavaScript

In my three.js project or JavaScript, I want to preload contents with a loading bar. While I am familiar with using action-script to achieve this, I am struggling to do the same in JavaScript: Here is the code snippet: var loader = new THREE ...

Comparing the use of .on in a directive versus in a controller

When deciding between attaching a directive to an element or binding an event inside the controller, what is considered best practice? Directive <openread-more what-to-expand="teds-bets-readmore" /> myApp.directive('openreadMore', functi ...

Storing FileSystemInfo Array in a File

I am currently working on a project where I need to save an array of FileInfo and DirectoryInfo objects to use as a log file. The purpose is to capture a snapshot of a directory (including subdirectories) at a specific moment for future comparison. To achi ...

The operation in Mongo DB carried out a $pull to eliminate the ObjectId("... id") from the nested sub-array

I've scoured every nook and cranny of the internet in an attempt to resolve this issue, but so far I've come up empty-handed. My goal is to use the mongodb $pull function to remove an Object from an array nested inside a Schema. I've success ...

Why is there an alphabet or letter inside the brackets of an array? And why is this occurring inside a for loop?

How does the variable "x" function within the array's brackets and loop in the code snippet below? (This example demonstrates logic using C#) #include <iostream> #include <string> using namespace std; int main() { int myArr[5]; / ...

What method can I use in webpage coding to achieve this special highlight effect, and what is the official term for it?

Need help figuring out how to make an icon change from blue to white when selected. I've searched through Bootstrap, CSS, and HTML, but haven't found the solution yet. Any suggestions would be appreciated! https://i.stack.imgur.com/RK1PD.png ...

Replacing old items with new ones: AngularJS now pushes to array in service

I am attempting to update a list in the home.html file and then display the updated list in myOrders.html using ionic and angularjs. The issue I am facing is that whenever I add a new item to the array, it replaces all the previous items with the new one. ...

SheetJS is experiencing difficulties parsing dates correctly

Need help exporting an HTML table to an Excel file using the SheetJS library. Here's my code snippet: var table = document.getElementById("tableToExport"); var ws = XLSX.utils.table_to_sheet(table, { sheet: "Raport Odorizare", da ...

What was Douglas Crockford trying to convey with the term 'created in an alternate window or frame'?

What did Douglas Crockford mean when he mentioned that the is_array() test might not correctly identify arrays created in a different window or frame? var is_array = function (value) { return value && typeof value === 'object&apos ...

Issue with Google map displaying incorrectly when attempting to print

I am experiencing an issue with printing a Google Map using the JavaScript API V3. The problem I am facing is that the map is split into two parts, with the top and bottom sections overlapping each other. Here is the code snippet: var geocoder; var ...

Converting a Java List to a JSON Array using Jackson

Currently using Jackson for JSON serialization. Attempting to convert a Java List (containing string values) into a JSON array. Experimented with different methods, encountering issues along the way: 1. Using JsonGenerator's writeString method final ...

Trouble retrieving data from cross-domain JSON request in AngularJS

Struggling all day to retrieve the JSON data from this specific URL: As a beginner in cross-domain calls, I attempted using JSONP and $get.JSON methods without any luck. My main goal is to extract the information from that URL link and store it in an Angu ...

Tips on resolving the error message "Property ... is not present on type 'IntrinsicAttributes & ...' in NextJS"

In my nextjs application, I have a Navbar component that accepts menu items as props: <Navbar navitems={navigationItems} /> The navigationItems prop is an array of objects. Within the Navbar component, I have defined the following: export interface ...