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

Generating a JSON array using PHP

Hey there, I'm currently working on creating an array for easier access to some data in my ESP32 project. The issue I'm facing is with the Json 6 library - specifically, I can't seem to access the contents of the array as intended. For examp ...

Unravel complex JSON arrays in PHP with multiple dimensions

I am struggling to decode a JSON array and make it readable without receiving an error. My desired output should look like this: image1 image2 image3 $json = ' { "acf" : { "hero_banner" : [ { "banner_image" : ...

Issue with VueJs and ChartJs not displaying custom options when making an API call

Having trouble populating my chart with data from the API. Despite setting extraOptions for my chart, it defaults to default options when rendered. Here is the component code: import { Bar, mixins } from 'vue-chartjs'; export default { name: ...

Choose items from a nested array

This database object contains the following information: { "_id" : { "$oid" : "53a9ce071e24a7a0a4bef03a"} , "name" : "name4" , "sections" : [ { "id" : "sectionId1" , "subs" : [ { "name" : " ...

Button press triggers the fadeIn function successfully, but the keypress event does not have the same effect

I'm currently facing an issue with two div elements on my webpage. I want only one of them to be visible at a time, depending on which key is pressed. If the 1 key is pressed, I want 'div1' to fadeIn (if it's not already visible) and fo ...

Listening to multiple events in AngularJS using `$scope.$on`

I am faced with a situation where I need to respond to two different events being transmitted via $scope.$emit and take action only when both have occurred. For example, if the events are triggered in the following sequence: $scope.$emit('first&apos ...

Automated Copy and Paste Feature - JavaScript using Ajax

I am working on a unique auto-increment IMDB ID grabber that retrieves the ID as you type the name of a TV show. Currently, I have managed to create functionality where it checks if the field is empty; if not, it displays a button that directs you to a pag ...

How can cookies be managed with JavaScript, Express.js, or Node.js?

Could anyone advise on the optimal approach for managing cookies - through Express.js, Node.js, or client-side JavaScript/jQuery? I'm feeling a bit uncertain about security implications. Your assistance and insights are greatly appreciated. ...

The inline script is deemed non-compliant as it infringes upon the Content Security Policy directive: "script-src 'self'"

My chrome-extension is built using react-create-app. However, I encountered an error when running npm run build in react-create-app: Refused to execute inline script because it violates the following Content Security Policy directive: "script-src &apo ...

Transforming disorderly string column into wide structure

I am facing a challenge with the dataset provided below: Input date data value 2021-01-01 a=uk_b=goo1_c=brandA_d=phrase_d1 for pedro 2020 20 2021-02-01 a=us_b=goo2_c=brandB_d=phrase_d2 for peter 2020 ...

Having trouble with the $.post method not loading my PHP file in my

I followed a tutorial on YouTube to copy the code, adjusted the database connection and SELECT items to fit my existing DB, but I'm struggling to get the JS file to load the PHP file. When I use Chrome's "inspect" tool, it shows that the JS file ...

Is XML to JSON the standard format?

Imagine you have an XML file structured like this: <CATALOG> <CD> <TITLE>Empire Burlesque</TITLE> <ARTIST>Bob Dylan</ARTIST> </CD> <CD> <TITLE>Empire Burlesque</TITLE> <ARTIST&g ...

Utilizing jQuery to toggle nested divs within identical parent divs when they contain more than three elements using the :nth-child selector

Within my HTML markup, I have created two parent div elements that are exactly the same but contain different content. My goal is to have a functionality where if a parent div has more than 3 child div elements, a "show more" text will be displayed at the ...

Efficient method for retrieving the values of each cell in a row within an array

I've got a standard table here - 6 columns, multiple rows, all filled with data. Right now, my goal is to collect all this table data into an array: tableData(0) = "1, Hans, Testperson, Munich, Germany" tableData(1) = "2, Petra, Tes ...

When the user clicks on the element, swap out the current image tag

Is it possible to replace the <img src> code in a textarea with image URLs when a button is clicked? <textarea> <img src="https://example.com/image1.gif" alt="image1" /></a> <img src="https://example.com/image2.gif" alt="ima ...

The FatSecret Sharp API does not support starting an asynchronous operation at the current moment

I'm currently working on an ASP.NET project where I need to integrate the Fatsecret API using a wrapper called FatSecret Sharp. However, when attempting to make a server side method call from my JavaScript script, I encounter an error. I am seeking gu ...

Lightbox2 is looking to reposition the caption to the right of the image

Can anyone help me understand how to move the caption, found in data-title, from underneath an image to the right of the image? I'm not very familiar with HTML/CSS, but it looks like the image is enclosed within a div called .lb-outerContainer, and t ...

Is there a way to extract the "validade" value from the array and retrieve it exclusively?

The following array contains data: {"status":true,"data":[{"id":1,"pessoa_id":75505,"created_at":"2022-02- 01T17:42:46.000000Z","holder":"LEONARDO LIMA","validade&quo ...

Implementing seamless redirection to the login page with Passport in Node.js

I have encountered a persistent issue while using node.js, express, and passport. After successfully validating the user with passport, my application keeps redirecting back to the login page instead of rendering the index page. Is there a problem with the ...

Executing a JavaScript function using document.write()

When I try to click on the SWF part1 links within the document.write() function in order to call the openswf function, nothing happens. Here is my code: <html> <a href="#" onclick="Popup();">show popup</a> <script> functio ...