What is the best way to access a specific key value within an array of objects nested within other objects?

In my originalArrayData, I have an array structured as follows:

https://i.sstatic.net/soqgt.png

Expanding on this:

https://i.sstatic.net/H4jXh.png

The first item in the array is an object that contains multiple other objects. Here is an example of the contents of the array:

originalArrayData = [{
    "16": {
        "id": 22,
        "grid_row_id": 5,
        "grid_col_id": 16,
        "data": "10",
        "created_at": "rertte",
        "error_mgs": null
    },
    "header": "Row 2",
    "id": 5
},
{
    "17": {
        "id": 31,
        "grid_row_id": 9,
        "grid_col_id": 17,
        "data": "14",
        "created_at": "rtyhtyjtdyj",
        "error_mgs": null
    },
    "header": "Row 1",
    "id": 6
},
{
    "18": {
        "id": 35,
        "grid_row_id": 9,
        "grid_col_id": 12,
        "data": "55",
        "created_at": "thrtuhrs",
        "error_mgs": null
    },
    "header": "Row 1",
    "id": 6
}...........

Assume I have an array of ids, represented as follows (the numbers can vary and there may be 1, 3, or more items):

arrayOfIds: [16 , 17]

If the value of grid_col_id matches any value in arrayOfIds, how can I extract the 'data' value from each object and store it in a new array?

I already know how to extract an array of all ids from each first object in the array:

let data = this.arrayList.map((obj) => obj.id);

The result is: [5,6,7,8,9]. However, this is not what I need for my current task. So, I have the following approach:

var targetArr = []

this.originalArrayData.forEach(item=> {
    item.forEach(ins => {
        if(arrayOfIds.includes(ins.grid_col_id)
            targetArr.push(ins.data)
    })
})

This results in an error message: TypeError: row.forEach is not a function

My GOAL is: [10, 14, ...]

The target array includes 10 and 14 because, based on the originalArrayData, if grid_col_id matches any value from arrayOfIds, we extract the "data" value and place it into a new array.

How can I achieve this target array?

Answer №1

Here is a step-by-step guide on how to achieve this with explanations provided in the code comments:

let od  = [{
    "16": {
        "id": 22,
        "grid_row_id": 5,
        "grid_col_id": 16,
        "data": "10",
        "created_at": "rertte",
        "error_mgs": null
    },
    "header": "Row 2",
    "id": 5
},
{
    "17": {
        "id": 31,
        "grid_row_id": 9,
        "grid_col_id": 17,
        "data": "14",
        "created_at": "rtyhtyjtdyj",
        "error_mgs": null
    },
    "header": "Row 1",
    "id": 6
},
{
    "18": {
        "id": 35,
        "grid_row_id": 9,
        "grid_col_id": 12,
        "data": "55",
        "created_at": "thrtuhrs",
        "error_mgs": null
    },
    "header": "Row 1",
    "id": 6
}]


let filter = [16, 17];

// convert original data into a flat array of objects
let dd = od.map(x => 
   // select object properties only
   Object.values(x)
   // filter out primitive types
   .filter(y => typeof y === "object")) 
   // flatten the array 
   .flat()
  
let result = dd  
   // filter objects based on the ids in the filter array
  .filter(x => filter.includes(x.grid_col_id))
  // select only the data property
  .map(x => x.data)

  console.log(result);

Answer №2

Here is the code snippet for you:

const input=[{"16":{id:22,grid_row_id:5,grid_col_id:16,data:"10",created_at:"rertte",error_mgs:null},header:"Row 2",id:5},{"17":{id:31,grid_row_id:9,grid_col_id:17,data:"14",created_at:"rtyhtyjtdyj",error_mgs:null},header:"Row 1",id:6},{"18":{id:35,grid_row_id:9,grid_col_id:12,data:"55",created_at:"thrtuhrs",error_mgs:null},header:"Row 1",id:6}];

const arrayOfIds = [16 , 17];

const format = (array) => {
    return array.reduce((result, el) => {
        const key = Object.keys(el).find((key) => 'object' === typeof el[key]);
        
        if(arrayOfIds.includes(+key)){
            result.push(+el[key].data);
        }

        return result;
    }, []);
};

console.log(format(input));

Answer №3

Here's an alternate method that closely mirrors your initial approach.

To achieve this, you can utilize Object.keys, Object.hasOwn, and Array.prototype.find in JavaScript to retrieve the key associated with the property grid_col_id:

const originalArrayData = [{
    "16": {
        "id": 22,
        "grid_row_id": 5,
        "grid_col_id": 16,
        "data": "10",
    },
    "header": "Row 2",
    "id": 5
},
{
    "17": {
        "id": 31,
        "grid_row_id": 9,
        "grid_col_id": 17,
        "data": "14",
    },
    "header": "Row 1",
    "id": 6
},
{
    "18": {
        "id": 35,
        "grid_row_id": 9,
        "grid_col_id": 12,
        "data": "55",
    },
    "header": "Row 1",
    "id": 6
}]

const arrayOfIds = [16, 17]
const targetArr = []

originalArrayData.forEach(d => {
    const keyOfObjectWithGridCol = 
        // Obtain an array of all keys in the object
        Object.keys(d)
        // Find the key of the nested object that contains grid_col_id
        .find(key => Object.hasOwn(d[key], 'grid_col_id')) // Find property

    if (arrayOfIds.includes(d[keyOfObjectWithGridCol].grid_col_id)) {
        targetArr.push(d[keyOfObjectWithGridCol].data)
    }
})

console.log(targetArr) // Output: [10, 14]

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

Proper method for incorporating a single database pool across an Express application

Disclaimer: This issue pertains to singleton objects in Node.js and not DB pools. While developing an Express.js application with the mysqljs node module for DB connections, I am interested in creating a single pool object that can be reused across differ ...

Oops! Looks like Laravel has hit its limit with 256 nesting levels in the function

I recently encountered a problem while working with an API that provides a mixture of JSON, STDClass, and Arrays. My main focus was extracting specific data from this nested structure which I managed to accomplish. However, the issue arose when I attempted ...

Anticipated the presence of a corresponding <div> within the server's HTML nested in another <div>

I've encountered a troubling error on my website while using Next.js. The error is causing layout issues and upon investigation, it seems that the device detection hook is at fault. Here's the hook in question: const isBrowser = typeof window !== ...

getting a null response when using the map feature - coding battles

Given an array filled with integers, my goal is to generate a new array containing the averages of each integer and its following number. I attempted to achieve this using the map function. var arr = [1,2,3,4]; arr.map(function(a, b){ return (a + b / ...

Values returned by XmlHttpRequest

When it comes to returning data from an XmlHttpRequest, there are several options to consider. Here's a breakdown: Plain HTML: The request can format the data and return it in a user-friendly way. Advantage: Easy for the calling page to consume ...

How to break up a text file into an array using regular expressions in PHP

I have a string containing changelog text that I need to split into individual entries within an array. For example, here is the changelog text stored in a variable called $changelog_txt: The Changelog Text Goes Here... The desired output should be an a ...

Creating an Angular table row that can expand and collapse using ng-bootstrap components is a convenient and

I need assistance with an application I am developing, where I want to expand a table row to display details when it is clicked. The issue I am facing is that currently, all rows expand and show the data of the clicked row as seen in the image result below ...

Top-speed 3D to 2D transition with Numpy

I have a 3D array of binary data that I need to convert into three 2D images - one from the side, one head-on, and one bird's eye view. This is the code I've come up with: for x in range(data.shape[2]): for y in range(data.shape[0]): ...

I seem to be making a mistake in parsing a single object JSON - can anyone help me

I have been struggling to figure out why I am getting an "unrecognized selector sent to instance" error while trying to parse a simple JSON in Xcode. I have successfully done this in the Android version of my app, but now I am stuck. Here is the code snipp ...

Is there a way to implement DnD functionality on a dynamically generated div element within an HTML page using Dojo

Is it possible to implement drag and drop functionality on dynamically generated div elements using Dojo? I have experimented with various methods to incorporate this feature. Below is a snippet of my code: var inputdiv = document.createElement('div& ...

In PHP, utilizing a for loop to create an array and then employing a separate for loop to manipulate that array

Within my for loop, I am creating two arrays: foreach ($data as $key => $value) { ........ ........ $user_insert[] = [ 'keyy' => $value, 'key' => $value, .... ... ... ]; $someArray1[ ...

The forEach method is supported on FileList in CRA/Next JS applications, however, it does not work on FileList in Next JS applications created using

I've encountered a puzzling issue. While using forEach on a FileList in a website created with CRA and then migrated to Next JS, the code runs smoothly. However, when I recreated the website using create-next-app, forEach doesn't work on the file ...

Utilizing Angular to automatically extract keys from nested objects in a response

In my Angular application, I am facing a challenge with accessing nested responses from the server. The data structure contains multiple responses within one parent object, and I am struggling to dig deeper into it. Here is the code snippet I have so far: ...

Ensuring Code Execution Order in NODE.JS

I've encountered an issue with my code that involves parsing a pcap file, storing the data in an array data = [], and then writing it to a JSON file: var fs = require("fs"); var pcapp = require('pcap-parser'); var hex = ""; var data = []; v ...

Execute the controller function with the value as a parameter

I encountered an issue while attempting to call a function in the c# controller and passing a value. The error message I received was: `'Unable to get property 'then' of undefined or null reference'. I also included the Driver Model but ...

Storing the API key returned by the Node.js store as a variable was

Just starting out with node and experimenting with A node.js library for the Pardot API I provide my userKey, email, and password to pardot, which returns an api_key. This is the code snippet I am using for authentication. Upon running my node server, I ...

Converting an array of date strings to a single string in JavaScript

Here is the JSON format I received with dynamic data: {"range":["2018-07-23T16:03:26.861Z","2018-07-23T16:03:26.861Z"]} Now, I need to convert this into the following format: range(20180723,20180723) Below is my code snippet : var data:Date[] = {"rang ...

Discovering the mean value from a data set in a spreadsheet

I have been tasked with creating an HTML page for a car dealership using JQuery and Bootstrap 5. The goal is to utilize Bootstrap 5 to accomplish the following: Set up a table with appropriate form input elements that allow users to input four (4) quarter ...

Three.js: Spherical boundary of an object that has been resized

When working with a collection of 3D shapes such as pyramids, cubes, octahedrons, and prisms, I encountered an issue with building described spheres around them. While it's straightforward to create the spheres using geometry.boundingSphere due to its ...

Initializing MongoDB server instance created by NodeJS using npm installation

I've recently installed mongodb on my OSX machine by running the command npm install mongodb in the myapp/node_modules directory while using node.js. However, I'm a bit confused because the mongodb official documentation states that to start mong ...