What is the process for generating a fresh array by extracting the values from an array of nested objects?

(This scenario is a bit more intricate compared to a previous query)

Here we have an array called originalArrayData:

originalArrayData = [{
    "16": {
        "id": 22,
        "grid_row_id": 5,
        "grid_col_id": 16,
        "data": "10",
        "created_at": "rertte",
        "error_mgs": null
    },
    "header": "BUTTERFLY HEADER",
    "id": 5
},
{
    "17": {
        "id": 31,
        "grid_row_id": 9,
        "grid_col_id": 16,
        "data": "14",
        "created_at": "rtyhtyjtdyj",
        "error_mgs": null
    },
    "header": "BUTTERFLY HEADER",
    "id": 6
},
{
    "18": {
        "id": 35,
        "grid_row_id": 9,
        "grid_col_id": 12,
        "data": "55",
        "created_at": "thrtuhrs",
        "error_mgs": null
    },
    "header": "PARROT HEADER",
    "id": 6
},
{
    "19": {
        "id": 36,
        "grid_row_id": 9,
        "grid_col_id": 12,
        "data": "31",
        "created_at": "rtyhtyjtdyj",
        "error_mgs": null
    },
    "header": "PARROT HEADER",
    "id": 7
},
{
    "20": {
        "id": 36,
        "grid_row_id": 9,
        "grid_col_id": 14,
        "data": "31",
        "created_at": "rtyhtyjtdyj",
        "error_mgs": null
    },
    "header": "OTHER HEADER",
    "id": 7
}...........

Let's assume we have an array of ids (these numbers could be random and there isn't always 2. There could be 1, 3, etc. array items)

arrayOfIds: [16 , 12]

If the value of grid_col_id exists in arrayOfIds, then for each object with the same grid_col_id, how can I generate a new array with new keys created using the "header" value, and the values of those keys being the sum of the "data" value from all items with the same grid_col_id.

TARGET / EXPECTED OUTPUT:

[{ "butterflyheader": 24, "parrotheader": 86, "category": "None"}]

EXPLANATION: If you examine each item in originalArrayData (for this example there are 4, but there can be many), the first 2 items share the same grid_col_id and header. For these two, the "data" equals to "10" and "14", which adds up to 24. Therefore, you obtain "butterflyheader": 24.

The same principle applies to parrotheader. All new keys are derived by converting the original "header" values into lowercase without spaces.

The element with the header "OTHER HEADER" is not included because its grid_col_id does not match any in arrayOfIds. "category": "None" remains constant and can be 'hard coded' into the new array.

To address this problem, I've formulated the following code:

        // creates an array of all innermost objects in the original array
        let tableDataFiltered = originalArrayData.map(item => 
            Object.values(item).filter(item => typeof item === "object")
        ).flat()

        // Retrieve all items with relevant grid_col_id
        tableDataFiltered.filter(item => arrayOfIds.includes(item.grid_col_id))

        // Headers to use as keys
        let headersAsKeys = tableDataFiltered.forEach(item => {
            item.header.toLowerCase().split(' ').join('')
        })

        Object.values(tableDataFiltered.reduce((acc, curr) => {
            acc[curr.category] = 'None';
            headersAsKeys.forEach(key => {
                acc[curr.category][key] += curr[key];
            })
            return acc;
        }, {}));

However, it returns an error stating that headersAsKeys.forEach is not a function.

How can I acquire the desired target array? =>

[{ "butterflyheader": 24, "parrotheader": 86, "category": "None"}]

Answer №1

To efficiently manage the data for each header, you can utilize the Array#reduce method along with an object.

const arr=[{"16":{id:22,grid_row_id:5,grid_col_id:16,data:"10",created_at:"rertte",error_mgs:null},header:"BUTTERFLY HEADER",id:5},{"17":{id:31,grid_row_id:9,grid_col_id:16,data:"14",created_at:"rtyhtyjtdyj",error_mgs:null},header:"BUTTERFLY HEADER",id:6},{"18":{id:35,grid_row_id:9,grid_col_id:12,data:"55",created_at:"thrtuhrs",error_mgs:null},header:"PARROT HEADER",id:6},{"19":{id:36,grid_row_id:9,grid_col_id:12,data:"31",created_at:"rtyhtyjtdyj",error_mgs:null},header:"PARROT HEADER",id:7},{"20":{id:36,grid_row_id:9,grid_col_id:14,data:"31",created_at:"rtyhtyjtdyj",error_mgs:null},header:"OTHER HEADER",id:7}];
const ids = [16 , 12];
let res = [arr.reduce((acc, {header,id,...rest})=>{
  let [{grid_col_id, data}] = Object.values(rest);
  header = header.toLowerCase().replaceAll(' ', '');
  if(ids.includes(grid_col_id)) 
    acc[header] = (acc[header] || 0) + +data;
  return acc;
}, {category: "None"})];
console.log(res);

Answer №2

To accomplish this task, a single loop is sufficient. While iterating over an object, simply check if the grid_col_id matches the desired value. If it does, add the data to the output object (initialized as { category: 'none' }), summing it up with any previous values. Finally, encapsulate the resulting object in an array.

const originalArrayData=[{16:{id:22,grid_row_id:5,grid_col_id:16,data:"10",created_at:"rertte",error_mgs:null},header:"BUTTERFLY HEADER",id:5},{17:{id:31,grid_row_id:9,grid_col_id:16,data:"14",created_at:"rtyhtyjtdyj",error_mgs:null},header:"BUTTERFLY HEADER",id:6},{18:{id:35,grid_row_id:9,grid_col_id:12,data:"55",created_at:"thrtuhrs",error_mgs:null},header:"PARROT HEADER",id:6},{19:{id:36,grid_row_id:9,grid_col_id:12,data:"31",created_at:"rtyhtyjtdyj",error_mgs:null},header:"PARROT HEADER",id:7},{20:{id:36,grid_row_id:9,grid_col_id:14,data:"31",created_at:"rtyhtyjtdyj",error_mgs:null},header:"OTHER HEADER",id:7}];
const arrayOfIds = [16, 12];

const outputObj = { category: 'none' };
for (const { header, id, ...rest } of originalArrayData) {
  const { grid_col_id, data } = Object.values(rest)[0];
  if (arrayOfIds.includes(Number(grid_col_id))) {
    outputObj[header] = (outputObj[header] || 0) + Number(data);
  }
}
console.log([outputObj]);

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

Tips for fixing the issue "Uncaught SyntaxError: Unexpected token S in JSON at position 0"

After referencing sols of SO, I am still unable to solve the error. I have a file dashboard.html which contains search conditions. When clicked, it calls loadtable.js. This loadtable.js file uses search.php to retrieve rows from a table. However, encount ...

Organize the array by property name and include a tally for each group

My current data structure looks like this: var data = [ { MainHeader: Header1, SubHeader: 'one'}, { MainHeader: Header1, SubHeader: 'two'}, { MainHeader: Header2, SubHeader: 'three'}, { MainHeader: Header2, SubHea ...

Error: [BITFIELD_INVALID_RANGE]: The bitfield flag or number entered is not valid: 3214336

Currently working on a Discord Dashboard project, but encountering an unusual error: Invalid bitfield flag or number 3214336. This issue arises when attempting to retrieve the guilds that a user has MANAGE_GUILDS permission for. Below is the snippet of my ...

What is the best way to assign string values from an array in data() to the src attribute of an image element?

I've been working on a feature where the <div.box> element appears based on the user's input through a form. In this project, I'm using vue3 and v-for to iterate over an array 'images' that contains URL strings linking to ima ...

Transform 3D mha images into 2D images using Python for the 2015 BRATS Challenge dataset

Looking to utilize either SimpleITK or wedpy for converting 3D images into 2D images. Alternatively, I aim to obtain a three-dimensional matrix and then break it down into multiple two-dimensional matrices. import SimpleITK as ITK import numpy as np #from ...

Utilize an array-variable in VBA to maximize the effectiveness of your SQL WHERE clause

Is there a way to insert an array, stored in a variable, into the WHERE clause of a SQL statement in VBA? recordset1.Open "SELECT * FROM [Table] WHERE [NettingSet] = '" & varRecord & "'" The original string is: recordset1.Open "SELECT ...

combination of Vue methods from a separate file

Having some trouble sharing a method in Vue across files. Despite trying various suggestions found through research, I haven't been able to make it work. I did manage to get mixins working within the same file, but couldn't figure out how to impo ...

What are some ways that we can enhance each other's value?

I am currently delving into the realm of Java-script, with the goal of creating an input field for numbers. My vision is to have a scenario where when a user enters a number in the input field, my script will display it in a paragraph or another text field ...

Creating a JSON object in PHP with a specific property is a common

What PHP array structure would be equivalent to the object with identical properties below: For instance... transform the 'columns' object into PHP using json_encode: jQuery('#example').dataTable( { "ajaxSource": "sources/objects.tx ...

AngularJS: Batch processing for saving multiple students simultaneously

I have been working on saving information about students, and I've written the code below. However, I'm unsure how to proceed from here. Any additional information or resources related to this topic would be greatly appreciated. <div ng-contr ...

What makes React Native unique when it comes to handling multiple data inputs?

Apologies for my limited English skills. I am trying to structure multiple data entries by adding separate JSON lines for each input, but currently it updates the previous data instead of creating a new one. Below is the sample code I am working with. var ...

The error message in AuthenticatedLayout.jsx on line 43 indicates a problem with trying to access properties of an undefined object, specifically the 'name'

I am encountering this issue react-dom.development.js:26923 Uncaught TypeError: Cannot read properties of undefined (reading 'name') at AuthenticatedLayout (AuthenticatedLayout.jsx:39:55) AuthenticatedLayout.jsx import { useState } from "re ...

Could someone kindly clarify the workings of this jQuery script for me?

I found this code online, but I'm struggling to comprehend its functionality. In order to make any edits for my needs, I need to understand how it operates. The purpose of this script is to close a panel with an upward slide animation when the "x" but ...

transforming JSON into CSV structure

I am attempting to utilize a JSON file as input data. Below is an excerpt of sample data. [ { id: 1671349531, name: "A Wild Restaurant Expansion", blurb: "We are looking to expand from our current location to a new and better facility...", goal: 17000, pl ...

Extract PHP variable and incorporate it into JavaScript code

After doing some research online, I was unable to find a solution to my issue. Can anyone provide assistance with this problem? I currently have a javascript variable that contains the name of a PHP session address. I am trying to access this session valu ...

Tips for exporting an image from a threeJS scene

I am looking to export a 2D image of my scene by simply clicking a button on my HTML page. I have tried adding some code to my function, but unfortunately, it doesn't seem to work and the image is not downloading. (I am using Chrome as my browser) con ...

Issue encountered while validating a dropdown selection within a form using JavaScript

I have a form that includes multiple options for users to choose from. My goal is to prevent users from selecting the same option more than once. I've written some JavaScript code for this purpose, but I'm encountering an issue with the alert mes ...

Markers on the map are not receiving the necessary click event handlers

The block of code below is designed to place markers on a map. However, it seems that the add Listener event is not properly attached to each marker. var mapDiv = document.getElementById("google-map"); var infoWindow = new google.maps.InfoWindow({ ...

Enhancing Function Calls for Better Performance in V8

Is V8 capable of optimizing repeated function calls with identical arguments? For instance, in the code snippet below, Variance is invoked twice with the same arguments. var Variance = require('variance'); function summary(items) { ...

select elements based on specific keys in the array

I have been working on a function that filters my array by keys: private function filterMyArray( ) { function evaluateKey( $value ) { return $value['type'] == 'video'; } return array_filter( $array, ...