Converting an unbroken series of string values into organized key-value pairs for easy reference

I assure you this is not a duplicated question. Despite my attempts with JSON.parse(), it seems to be ineffective.
Here's the issue at hand: I recently received assistance from an answer that was both crucial and enlightening. However, the code provided in that response has generated a result that I am struggling to extract individual values from as it appears as a seamless string of continuous values:

the following code snippet:

    var result = {};
  for ( var i = 0; i < arr.length; i++ ) {
  var key = "asset: " + arr[ i ].geo + ' ym: ' + arr[ i ].ym + ' venue: ' + arr[ i ].venue + ' value';
  result[ key ] = (result[ key ] || 0 ) + arr[ i ].value ;
    }
Logger.log(result);

transforms this given array:

    arr = [
{value:1.0, venue: "binance",  ym:20181.0, geo:"eur"}, 
{value:6.0, venue: "binance",  ym:20181.0, geo:"eur"},
{value:2.0, venue: "bitstamp", ym:20181.0, geo:"eur"}, 
{value:5.0, venue: "binance",  ym:20182.0, geo:"eur"}, 
{value:1.0, venue: "binance",  ym:20183.0, geo:"eur"}, 
{value:3.0, venue: "binance",  ym:20181.0, geo:"usd"}, 
{value:3.0, venue: "binance",  ym:20182.0, geo:"usd"}, 
{value:3.0, venue: "binance",  ym:20183.0, geo:"usd"}, 
{value:2.0, venue: "binance",  ym:20181.0, geo:"pop"}, 
{value:2.0, venue: "binance",  ym:20182.0, geo:"pop"}, 
{value:2.0, venue: "binance",  ym:20183.0, geo:"pop"}, 
{value:2.0, venue: "binance",  ym:20181.0, geo:"dot"}, 
{value:2.0, venue: "binance",  ym:20182.0, geo:"dot"}
];

and transforms it into an unbroken sequence of data:

{asset: eur ym: 20181 venue: bitstamp value=2.0, asset: eur ym: 20182 venue: binance value=5.0, asset: dot ym: 20183 venue: binance value=2.0, asset: eur ym: 20183 venue: binance value=1.0, asset: usd ym: 20181 venue: binance value=3.0, asset: sol ym: 20183 venue: binance value=1.0, asset: pop ym: 20183 venue: binance value=2.0, asset: dot ym: 20182 venue: binance value=2.0, asset: dot ym: 20181 venue: binance value=2.0, asset:...
    
<span>(truncated for brevity)</span>

...cad ym: 20183 venue: binance value=3.0, asset: sol ym: 20182 venue: binance value=1.0, asset: pop ym: 20182 venue: binance value=2.0, asset: pop ym: 20181 venue: binance value=2.0, asset: cad ym: 20181 venue: binance value=3.0, asset: cad ym: 20182 venue: binance value=3.0, asset: eur ym: 20181 venue: binance value=7.0}

I find myself unable to utilize this data effectively since extracting specific values - like in a standard array with result[i].value or result[i].ym - proves to be a challenging task due to its continuous format where isolating a particular part feels daunting. Despite verifying with Logger.log(typeof result); which returns object, I still encounter difficulties in extracting any meaningful information from it. While I deeply appreciate the assistance provided through this code, the fault lies solely with me. It stems from my lack of experience, preventing me from deciphering this result effectively at the moment.

Answer №1

This particular solution utilizes Google Apps Script.

The script imports an array, calculates weekly totals, and presents both the original array and the weekly results on the current spreadsheet.

function sumArray() {
  var arr=[{value:1.0, venue: "binance",  ym:20181.0, geo:"eur"},{value:6.0, venue: "binance",  ym:20181.0, geo:"eur"},{value:2.0, venue: "bitstamp", ym:20181.0, geo:"eur"}, {value:5.0, venue: "binance",  ym:20182.0, geo:"eur"}, {value:1.0, venue: "binance",  ym:20183.0, geo:"eur"}, {value:3.0, venue: "binance",  ym:20181.0, geo:"usd"}, {value:3.0, venue: "binance",  ym:20182.0, geo:"usd"}, {value:3.0, venue: "binance",  ym:20183.0, geo:"usd"}, {value:2.0, venue: "binance",  ym:20181.0, geo:"pop"}, {value:2.0, venue: "binance",  ym:20182.0, geo:"pop"}, {value:2.0, venue: "binance",  ym:20183.0, geo:"pop"}, {value:2.0, venue: "binance",  ym:20181.0, geo:"dot"}, {value:2.0, venue: "binance",  ym:20182.0, geo:"dot"}];
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();
  sh.clearContents();//clear active sheet
  sh.appendRow(['value','venue','ym','geo']);//append headers for array
  arr.forEach(function(e,i){
    sh.appendRow([e.value,e.venue,e.ym,e.geo]);
  });//append array
  var vObj={};
  arr.forEach(function(e,i){
    if(!vObj.hasOwnProperty(e.venue)) {vObj[e.venue]={};}
    if(!vObj[e.venue].hasOwnProperty(e.ym)) {vObj[e.venue][e.ym]=e.value;}else{vObj[e.venue][e.ym]+=e.value;}  
    if(!vObj.hasOwnProperty(e.geo)) {vObj[e.geo]={};}
    if(!vObj[e.geo].hasOwnProperty(e.ym)) {vObj[e.geo][e.ym]=e.value;}else{vObj[e.geo][e.ym]+=e.value;}
    if(!vObj.hasOwnProperty('ym')) {vObj['ym']={};}
    if(!vObj['ym'].hasOwnProperty(e.ym)) {vObj['ym'][e.ym]=e.value;}else{vObj['ym'][e.ym]+=e.value;}
  });//calculate week sums
  //Logger.log(JSON.stringify(vObj));
  var keys=Object.keys(vObj.ym);
  keys.unshift('')
  sh.appendRow(keys);//headers for weekly sums
  var vkeys=Object.keys(vObj);
  //Logger.log(vkeys);
  for(var i=0;i<vkeys.length;i++) {
    var row=[];
    row.push(vkeys[i]);
    var rkeys=Object.keys(vObj[vkeys[i]]);
    for(var j=1;j<keys.length;j++) {
      if(vObj[vkeys[i]].hasOwnProperty(keys[j])) {
        row.push(vObj[vkeys[i]][keys[j]]);
      }else{
        row.push('');
      }
    }
    sh.appendRow(row);//appending weekly sum
  }
}

An image of the output is available here:

https://i.stack.imgur.com/Phf3Y.jpg

Answer №2

Thank you for explaining the issue clearly. To address it, here is a suggested approach:

 arr = [
  {value:1.0, venue: "binance",  ym:20181.0, geo:"eur"}, 
  {value:6.0, venue: "binance",  ym:20181.0, geo:"eur"},
  {value:2.0, venue: "bitstamp", ym:20181.0, geo:"eur"}, 
  {value:5.0, venue: "binance",  ym:20182.0, geo:"eur"}, 
  {value:1.0, venue: "binance",  ym:20183.0, geo:"eur"}, 
  {value:3.0, venue: "binance",  ym:20181.0, geo:"usd"}, 
  {value:3.0, venue: "binance",  ym:20182.0, geo:"usd"}, 
  {value:3.0, venue: "binance",  ym:20183.0, geo:"usd"}, 
  {value:2.0, venue: "binance",  ym:20181.0, geo:"pop"}, 
  {value:2.0, venue: "binance",  ym:20182.0, geo:"pop"}, 
  {value:2.0, venue: "binance",  ym:20183.0, geo:"pop"}, 
  {value:2.0, venue: "binance",  ym:20181.0, geo:"dot"}, 
  {value:2.0, venue: "binance",  ym:20182.0, geo:"dot"}
];

var result = {};
for ( var i = 0; i < arr.length; i++ ) {
  var key = '~' + arr[ i ].geo + '~' + arr[ i ].ym + '~' + arr[ i ].venue + '~';
  if ( result[ key ] === undefined ) {
    result[ key ] = {asset: arr[ i ].geo, ym: arr[ i ].ym, venue: arr[ i ].venue, subtotal: 0};
  }
  result[ key ].subtotal += arr[ i ].value;
}

console.log( result );

In essence, continue to create keys based on grouping for subtotals. However, instead of having key/value pairs like...

"~eur~20181~binance~": 7

...where the value is only the total, transform the value into an object containing grouped field values along with the subtotal. The new key/value pairs will resemble...

"~eur~20181~binance~": {asset: "eur", ym: 20181, venue: "binance", subtotal: 7}

...allowing you to refer to the group's values (such as asset, ym, & venue) when iterating through the results.

Hoping this explanation proves helpful.

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

Guide to inserting text into an html element upon clicking an ASP:Button

In my code, there is a DIV that holds some text. Accompanying the text is an asp:Button. When this button is clicked, I aim to access and save this particular text. Nonetheless, it seems that once the button is clicked, the content of the DIV resets - lik ...

Extract a section of the table

I'm looking to copy an HTML table to the clipboard, but I only want to include the rows and not the header row. Here is the structure of the table: <table style="width:100%" #table> <tr> <th class="border"></th> ...

Add up the duplicate elements in two arrays

I have dynamically created two arrays with the same number of cells (where array.length is the same, representing a key and value association). Below are the arrays: barData.labels["Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "F ...

Converting hexadecimal to binary using Javascript or Typescript before writing a file on an Android or iOS device

Hey everyone! I'm facing a puzzling issue and I can't seem to figure out why it's happening. I need to download a file that is stored in hex format, so I have to first read it as hex, convert it to binary, and then write it onto an Android/ ...

The Angular model does not automatically refresh when the Space or Enter key is pressed

Having an issue with my editable div and the ng-trim attribute. Even though I have set ng-trim to false, pressing SPACE or ENTER does not increment the string length by one in the div below. Using Angular 1.3.x and wondering if anyone has any ideas on how ...

VUE JS - My methods are triggering without any explicit invocation from my side

I've encountered a frustrating problem with Vue JS >.<. My methods are being triggered unexpectedly. I have a button that is supposed to execute a specific method, but this method gets executed along with other methods, causing annoyance... Her ...

The functionality of .getJSON() in JSON/JQuery is not compatible with IE8 or IE9 browsers

It seems that this particular code is not functioning properly in IE8/IE9, and I am uncertain whether it is caused by the JSON or JQuery .getJSON() element. The main objective of this code is to retrieve data from foursquare and present it on a webpage. I ...

The final condition of the ternary operator fails to render if the specified condition is satisfied

Having trouble identifying the issue with this ternary statement. The last element (blurredscreen) is not appearing when authStatus !== "authenticated". return ( <> <div key={"key-" + id}> {isO ...

Manage and preserve your node.js/express sessions with this offer

Currently, I am working on a web application that encounters an issue where every time fs.mkdir is called, all the current express sessions are deleted. This causes me to lose all session data and I need a solution to keep these sessions intact. I have att ...

Using PHP to send a JSON request via cURL

I am attempting to make a cURL request in PHP. The request I am trying to send is as follows: $ curl -H 'Content-Type: application/json' -d '{"username":"a", "password":"b","msisdn":"447000000001","webhook":"http://example.com/"}' http ...

Building custom directives on AngularJS pages without a specified ng-app module

On some of my basic pages, I don't need to specify a particular application module in the ng-app attribute. However, these pages do utilize some custom directives that I have created. To keep things organized, I have placed all of my directives withi ...

React Native backhandler malfunctioning - seeking solution

Version react-native-router-flux v4.0.0-beta.31, react-native v0.55.2 Expected outcome The backhandler should respond according to the conditions specified in the backhandler function provided to the Router props. Current behavior Every time the har ...

Clicking on a dynamically generated link will not result in the file being downloaded

I have a list of document names and IDs retrieved from a database, displayed in an unordered list like this: <ul id="list"> <li onmouseover="onHover(docNumber)"> <a herf="#" id="docNumber">DocName</a> </li> </ ...

Using Rails and Haml to Implement Smooth Scrolling with Jquery and CoffeeScript

Looking to accomplish a straightforward task using CoffeeScript, Rails, and Haml. While I don't have much experience with CoffeeScript, I'm eager to experiment. The goal is to have the view scroll to a specific div id when a button is pressed. A ...

What is the best way to implement a sidebar closing animation?

Utilizing both react and tailwindcss, I successfully crafted a sidebar menu that elegantly appears from left to right when the user clicks on the hamburger icon. However, my attempts to create a reverse animation as the sidebar disappears from right to lef ...

The issue with hiding and showing elements using JavaScript during drag and drop functionality

In my code, I have two boxes with IDs box1 and box2, These boxes can be dragged and dropped into the boxleft element, Upon dropping them, the background image is removed and only the name appears in the box, My issue is that when loading values into box ...

When a new marker is clicked on Google Maps, the previous Infowindow will automatically close

Here are some specific locations to consider: var places = [{ "id": 1, "ReferenceNumber": "52525252525", "Address" : "School" , "Latitude": "21.585486", "Longitude": & ...

Arrange an array of objects by making a nested API call in Angular

My task involves sorting an array of objects based on the response from the first API call in ascending order. The initial API call returns a list of arrays which will be used for the subsequent API call. The first API call fetches something like this: [0 ...

How can I notify an error in CoffeeScript/JavaScript when a parameter is not provided?

Initially, I believed that my code was clever for accomplishing this task: someFunction = (arg1, arg2, arg3) -> if _.some(arguments, (a) -> a is undefined) throw new Error "undefined parameter" My goal was to throw an error if any of the para ...

Error message: The module '@project-serum/anchor' does not export the object 'AnchorProvider' as intended

I encountered an issue while attempting to run my react application. The issue: Attempted import error: 'AnchorProvider' is not exported from '@project-serum/anchor'. The import declaration in my code: import idl from './idl.json ...