determine the proportion of the item

My function is supposed to map an object to create new keys. The new key "percent" is meant to calculate the percentage of each value of the key "data". It should be calculated as the value divided by the sum of all values. However, for some reason, it's not working correctly.

 

var myObject = {
  id1: {
  "value 1": 3,
  "value 2": 2
  },
  id2: {
  "value 1": 2,
  "value 2": 2
  },
  id3: {
  "value 1": 4,
  "value 2": 3
  }
};
 
 var series = _(myObject).map(function(g, key) {
 
var total = 0;
  for (var i in Object.values(g)) {
  total += Object.values(g)[i];
  }
 
  return {
  type: 'column',
  name: key,
  total: total,
  data: Object.values(g),
  percent:Object.values(g)/total
   };
});
console.log(series)

The expected result should look like this:

[{
 "type": "column",
 "name": "id1",
 "total": 5,
 "data": [ 3, 2 ],
 "percent": [ 0.6, 0.4 ],
}, {
 "type": "column",
 "name": "id2",
 "total": 4, 
"data": [ 2, 2 ],
 "percent": [ 0.5, 0.5 ],
}, {
 "type": "column",
 "name": "id3",
 "total": 7,
 "data": [ 4, 3 ],
 "percent": [ 0.57, 0.43 ],
}]

Answer №1

If you want to map new objects, one approach is to extract the key/value pairs, calculate the total of the values, and then determine the desired percentage (not based on 100, but on 1).

var object = { id1: { "value 1": 3, "value 2": 2 }, id2: { "value 1": 2, "value 2": 2 }, id3: { "value 1": 4, "value 2": 3 } },
    result = Object.entries(object).map(([name, values]) => {
        var data = Object.values(values),
            total = data.reduce((a, b) => a + b, 0),                
            percent = data.map(p => p / total);

        return { type: 'column', name, total, data, percent };
    });
 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

This code snippet is written for Internet Explorer using ES5 syntax.

var object = { id1: { "value 1": 3, "value 2": 2 }, id2: { "value 1": 2, "value 2": 2 }, id3: { "value 1": 4, "value 2": 3 } },
    result = Object.keys(object).map(function(name) {
        var data = Object.keys(object[name]).map(function (k) { return object[name][k]; }),
            total = data.reduce(function (a, b) { return a + b; }, 0),                
            percent = data.map(function (p) { return p / total; });

        return { type: 'column', name: name, total: total, data: data, percent: percent };
    });
 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To achieve the desired outcome, you can utilize Object.keys() along with Object.values().

DEMO

ES6

var myObject = {id1: {"value 1": 3,"value 2": 2},id2: {"value 1": 2,"value 2": 2},id3: {"value 1": 4,"value 2": 3}};

let result = Object.keys(myObject).map(v => {
  let data = Object.values(myObject.id1),
    sum = data.reduce((r, x) => r + x);

  return {
    type: 'column',
    name: v,
    total: sum,
    data: data,
    percent: data.map(p => p / sum)
  }
});

console.log(result);
.as-console-wrapper {max-height: 100% !important;top: 0;}

ES5

var myObject = {id1: {"value 1": 3,"value 2": 2},id2: {"value 1": 2,"value 2": 2},id3: {"value 1": 4,"value 2": 3}};

let result = Object.keys(myObject).map(function(v) {
  let data = Object.values(myObject.id1),
    sum = data.reduce(function(r, x) {return r + x});

  return {
    type: 'column',
    name: v,
    total: sum,
    data: data,
    percent: data.map(function(p){return  p / sum})
  }
});

console.log(result);
.as-console-wrapper {max-height: 100% !important;top: 0;}

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

Developing a unique attribute using AngularJS

As a beginner in AngularJS, I am experimenting with creating directives to manipulate the background-color of a <div> based on specific conditions. I aim to write code like this within my view: <div effect-color="#2D2F2A">content here</div& ...

When a JavaScript/jQuery open window popup triggers the onunload event after the about:blank page has been

Imagine you have a button that triggers a popup using window.open(): <button id = "my-button">Open window</button>​ You also want to detect when this popup window closes. To achieve this, you can use the following code: $('#my-button& ...

Display a close button for every individual item and use JavaScript to conceal the current item

I have a list that contains input fields along with delete link elements. I want to display the delete link element when the user hovers over the respective input field. Additionally, clicking on the close button (X) should hide the entire list item (li) f ...

Working with jQuery: Retrieving the ID of an element that is generated dynamically

Looking for some guidance: I'm working on dynamically creating a table based on the response from an AJAX call. The table includes headers and rows, with new rows added using the "after" function. However, I'm facing an issue with accessing the ...

The bond between TypeORM and express

I am working on establishing Many-to-One and One-to-Many relationships using TypeORM and MySQL with Express. The database consists of two tables: post and user. Each user can have multiple posts, while each post belongs to only one user. I want to utilize ...

What could be the reason for the malfunctioning transition effect in my slider animation?

Having trouble getting my slider animation to work. I've tried different CSS styles but the slide transition is not functioning as expected. When one of the buttons is clicked, I want the slide to change from right to left or left to right. Can anyone ...

Ignoring page redirects in Node.JS

Directories are organized as follows: -public -landing -landing.html -Login -login.html -register -register.html -routes HTMLroutes APIroutes - server.js All commented code are attempts I have made without success if (bcry ...

Utilizing JSON data from Jade in local JavaScript: A comprehensive guide

Attempting to utilize a JSON object (the entire object, not just a portion) from Node via Jade in my local myScript.js. Here is what my Jade file looks like: span(class="glyphicon glyphicon-pencil" onclick="confirm(\"#{myJSON.taskid}\", \" ...

Tips for properly linking external JavaScript files to HTML documents

I decided to delve into the world of HTML and stumbled upon this interesting js fiddle link http://jsfiddle.net/xfkeM/ Now, I am attempting to construct a basic webpage, but unfortunately, the desired output seems to be eluding me. Below is a snippet of ...

Even after implementing a setTimeout function, both Promises and Axios requests are still resulting in a

Recently, I've encountered an issue with the Reverse Geocode API from TomTom. The problem arises when I send multiple latitude and longitude coordinates (around 72 of them) to the API, resulting in frequent 429 responses. To address this issue, I att ...

Ways to exit the current browser window?

Is there a way to close the current browser window using JavaScript or another language that supports this functionality? I've tried using the window.close() function, but it seems to only work for windows opened with window.open(). Thank you in adv ...

The XML information vanished during the transformation into JSON format

After converting XML to JSON using multiple conversion libraries, I noticed that the property name attributes and Item name attributes were lost. Why is this happening? Does anyone have suggestions on how I can modify my XML to make it more compatible for ...

Modifying the input placeholder color with ng-style

I am working on setting the color of my input placeholder using a dynamic color defined in a $scope variable in my controller for my HTML code. The $scope variable is structured as follows: $scope.primaryColor={"color":colorVar}; //colorVar represents th ...

In need of assistance with filtering lists using JQuery

Hi there! I'm looking to modify a list filtering function by targeting multiple ul tags within the same div instead of just filtering li elements. Any ideas on how this can be achieved? Below is my JavaScript code: $( document ).ready(function() { ...

Utilizing a child component in React to trigger a function on its sibling component

Trying to put this question into words is proving to be a challenge. I am wondering in React, if there is a way for a child component that is deeply nested (2 levels deep from the parent) to trigger a function on another component that it has a sibling rel ...

Arrays Filtering without Containing Elements

Is there a utility function in Knockout to filter one array based on another array, or will I need to use JavaScript? First : var obj1 = [{ "visible": "true", "id": 1 }, { "visible": "true", "id": 2 }, { "visible": "true", "id": ...

Transform specific data binding values into JSON format using Knockout.js

Just dipping my toes into the world of knockoutjs, I've got this viewmodel set up: var Testing = function(){ this.Username = ko.observable(""); this.Password = ko.observable(""); this.email = ko.observable(""); } I'm tasked with ...

Tips for preventing the browser from freezing when incorporating a large HTML chunk retrieved through AJAX requests

I've developed a web application that showcases information about various items. Initially, only a small portion of the items are displayed at the top level. Upon loading the page for the first time and displaying these initial items, I make an AJAX r ...

Customizing the appearance of a Form.Check (checkbox) component in React Bootstrap

I am new to React and Bootstrap. I have a question about styling Form.Check (checkbox) components. How can I customize the default appearance to achieve a different look, such as a switch or another style? Here is what I have attempted so far (I tried app ...

Implementing Materialize CSS functionality for deleting chips

I've been attempting to extract the tag of a deleted chip from the div within the Materialize chips class, but I'm hitting roadblocks. My failed attempts so far: $('.chips').on('chip.delete', function(e, chip){ console.lo ...