What is the process for delineating a smaller object within a larger one?

The current data structure I am handling:

this.currentData = [
  {
    "1304": {
      "id": 6458,
      "data": "Data1",
      "created_at": "2020-10-20 23:16:38",
      "updated_at": "2020-10-20 23:16:38"
    },
    "1305": {
      "id": 6463,
      "data": "Data4",
      "created_at": "2020-10-20 23:16:38",
      "updated_at": "2020-10-20 23:16:38"
    }
  }
]

Desired data structure output:

this.desiredData = [
  {
    "1304": {
      "id": 6458,
      "data": "Data1",
      "created_at": "2020-10-20 23:16:38",
      "updated_at": "2020-10-20 23:16:38"
    },
    "1305": {
      "id": 6463,
      "data": "Data4",
      "created_at"": "2020-10-20 23:16:38",
      "updated_at"": "2020-10-20 23:16:38"
    }
  }
]

In essence, the initial array contains two objects with nested objects (this.currentData).

To achieve the desired outcome, I need to extract specific elements from this.currentData based on a predefined list of numbers. For example, if arrayOfNumbers = [1304, 1305], I want to dynamically filter through the data and retrieve objects associated with these key indices.

The filtering process should be dynamic using variables like arrayOfNumbers which can be generated programmatically as shown in the code below:

this.filterArray = this.someObject.columns.map(Number);

Is there a method to accomplish this and generate the desired output without hardcoding values?

Refer to the end of the code snippet for the target data structure called this.desiredData

Answer №1

Caution: the effectiveness of this method is contingent upon the input provided. It may not raise an error if the input data is incorrect.

Explanation of operation:

  1. We iterate through theDataStructureIHave, transforming each outerObject in the array
  2. Object.entries(outerObject) provides key-value pairs of the object (similar to
    [[key1, value1], [key2, value2], [key3, value3]]
    )
  3. We use filter to select only keys present in the arrayOfNumbers. Remember that the array contains integers while the object's keys are strings, hence the need for parseInt. The notation ([key, _]) represents array destructuring where we extract [key, val] and designate key and value accordingly (unused values are denoted as _). We could opt for something like (keyValuePair) and access the key via keyValuePair[0]
  4. Object.fromEntries(...) reconstructs an object from the key-value pairs

const theDataStructureIHave = [{
    "1304": {
      "id": 6458,
      "data": "Data1",
      "created_at": "2020-10-20 23:16:38",
      "updated_at": "2020-10-20 23:16:38"
    },
    "1305": {
      "id": 6459,
      "data": "Data2",
      "created_at": "2020-10-20 23:16:38",
      "updated_at": "2020-10-20 23:16:38"
    },
    "1306": {
      "id": 6460,
      "data": "Data3",
      "created_at": "2020-10-20 23:16:38",
      "updated_at": "2020-10-20 23:16:38"
    },
    "1307": {
      "id": 6461,
      "data": "1227",
      "created_at": "2020-10-20 23:16:38",
      "updated_at": "2020-10-20 23:16:38"
    },
    "1308": {
      "id": 6462,
      "data": "12256",
      "created_at": "2020-10-20 23:16:38",
      "updated_at": "2020-10-20 23:16:38"
    },
    "header": null,
    "id": 500
  },
  {
    "1304": {
      "id": 6463,
      "data": "Data4",
      "created_at": "2020-10-20 23:16:38",
      "updated_at": "2020-10-20 23:16:38"
    },
    "1305": {
      "id": 6464,
      "data": "Data5",
      "created_at": "2020-10-20 23:16:38",
      "updated_at": "2020-10-20 23:16:38"
    },
    "1306": {
      "id": 6465,
      "data": "Data6",
      "created_at": "2020-10-20 23:16:38",
      "updated_at": "2020-10-20 23:16:38"
    },
    "1307": {
      "id": 6466,
      "data": "3574",
      "created_at": "2020-10-20 23:16:38",
      "updated_at": "2020-10-20 23:16:38"
    },
    "1308": {
      "id": 6467,
      "data": "25824",
      "created_at": "2020-10-20 23:16:38",
      "updated_at": "2020-10-20 23:16:38"
    },
    "header": null,
    "id": 501
  },
  {
    "1304": {
      "id": 6468,
      "data": "Data7",
      "created_at": "2020-10-20 23:16:38",
      "updated_at": "2020-10-20 23:16:38"
    },
    "1305": {
      "id": 6469,
      "data": "Data8",
      "created_at": "2020-10-20 23:16:39",
      "updated_at": "2020-10-20 23:16:39"
    },
    "1306": {
      "id": 6470,
      "data": "Data9",
      "created_at": "2020-10-20 23:16:39",
      "updated_at": "2020-10-20 23:16:39"
    },
    "1307": {
      "id": 6471,
      "data": "3061",
      "created_at": "2020-10-20 23:16:39",
      "updated_at": "2020-10-20 23:16:39"
    },
    "1308": {
      "id": 6472,
      "data": "26696",
      "created_at": "2020-10-20 23:16:39",
      "updated_at": "2020-10-20 23:16:39"
    },
    "header": null,
    "id": 502
  }
]

const arrayOfNumbers = [1304, 1306];

const result = theDataStructureIHave.map(outerObject =>
  Object.fromEntries(Object.entries(outerObject).filter(([key, _]) => arrayOfNumbers.includes(parseInt(key))))
);

console.log(result)

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

What is the best way to incorporate white space in Bootstrap until a specific element is at the top of the screen?

I want to enhance my website design in Bootstrap 4 by having an image appear at the top of the user's screen when a certain button or image is clicked. This can be achieved by adding white space to the bottom of the website so that the image remains v ...

Can someone help me figure out how to trigger my function after my jQuery 'each' function has completed along with all the AJAX calls it includes?

Hello all, seeking some guidance here. I have experimented with various solutions from SO and other sources. This particular one caught my attention as I tried to ensure that my function wouldn't execute until all ajax calls were completed. However, I ...

Random YQL queries intermittently experience failures

I have been using YQL to retrieve data for a specific stock to display on my webpage. Periodically, the call to fetch the stock data fails inexplicably. A simple page refresh usually resolves the issue, with a success rate of about 75% and failure rate of ...

personalized XMLHttpRequest method open

var open = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(method, uri, async, user, pass) { this.addEventListener("readystatechange", function(event) { if(this.readyState == 4){ var self = this; var respons ...

"Locate" multiple conditions using mongoose

Seeking to retrieve data from my mongoDB database using mongoose filters. Each user object in the database contains fields like "Region" or "Sector". Currently, retrieving users that contain the keyword "region" in their object like this: // Filtering h ...

Attempting to create intricate nested JSON structures using JOLT transformation

Currently, I am facing challenges in constructing a complex nested array of JSON objects. Despite my efforts using JOLT, I have not been able to achieve the desired structure. Any assistance on this matter would be greatly appreciated. I've been stri ...

What is the method for performing a MongoDB left join while retaining documents that do not have a match on the right side?

Forgive my newness to this topic, but I am attempting a left outer join in MongoDB/NodeJS and seeking assistance. My goal is to retrieve all matching documents from the left table, even if they do not have a match on the right. Within my database, I have a ...

What could be causing the presence of when I JSON encode an array?

While I'm in the process of creating arrays and converting them into JSON strings, I came across an unusual issue. Some of the strings are unexpectedly adding \r\n at the beginning and end when I encode them to JSON format. These particular ...

Data retrieval on dashboard through ajax is not functioning properly

I have a dashboard with a partial view called SIM Balance. This view is intended to display the number of SIM cards issued to users on a daily basis. I have configured the controller as follows: public function actionSimbalance() { // SQL query to fe ...

Using AngularJS to dynamically assign classes with values derived from an ng-repeat loop

I'm attempting to assign a class to a table row using ng-class based on the value of ng-repeat. I have searched online and found examples that involve calling a function. Is it possible to simply set ng-class with a value instead of using a function? ...

What is the method for retrieving array elements within an object?

I have an array filled with multiple objects, each containing their own array of sub-objects. My objective is to iterate through the "subMenuItems" array within each object and display the values inside. Here's the Array I'm working with: export ...

Arrange the 2D array in JavaScript by utilizing both categories

Looking to organize a 2D array based on two specific criteria: [ [ "the,", 3 ], [ "who,", 3 ], [ "take,", 4 ], [ "over,", 4 ], [ "world,", 5 ] ] Sort by number in ascending order Then arrange alphabe ...

Adjust the tooltip image alignment to be offset from the cursor and appear at the bottom of the page

After creating a code snippet for image tooltips on text hover, I encountered an issue on my website where the bottom of the page expanded to accommodate the images. Is there a simple way to align the cursor at the bottom of the image when scrolling to the ...

Encountering a JavaScript issue where the error "function is undefined" appears when attempting to import the GL

I'm a beginner in Javascript and I'm currently working on a project that involves displaying a 3D model in a modal. Everything was running smoothly until I attempted to include an import statement. Once I added the line import {GLTFLoader} from & ...

Unable to view Bootstrap Icons in Gulp 4

I recently integrated the new bootstrap icons npm package into my project using Gulp 4, the latest version. Everything was installed successfully and was working smoothly. However, I encountered an issue when trying to declare the icon in my index.html fi ...

Creating dynamic content with Jquery templates using nested JSON objects

Currently, I am working on an app where I need to showcase a student's progress card using jQuery templates. However, I have encountered a difficulty while dealing with a JSON string as shown below: "[{"ID":1, "Name":"Frank", "Age":15, "Status":"Pass ...

Is there a way to retrieve values from TextFields and Select elements by simply clicking on a button?

I am currently working on a project using react, redux, and material ui. I need to retrieve data from a TextField in order to make an order. The code snippet below showcases my current implementation: <Select value={product.color_set[0].title}> { ...

AngularJS directive: handling child elements

Is there a way to structure the directive below in order to have access to all the ul elements within the link function? In the code snippet provided, when examining the elm (logged in console), it appears as a comment type and ul are displayed as sibling ...

How can I ensure that Chakra UI MenuList items are always visible on the screen?

Currently, I am utilizing Chakra UI to design a menu and here is what I have so far: <Menu> <MenuButton>hover over this</MenuButton> <MenuList> <Flex>To show/hide this</Flex> </MenuList> </ ...

SQL true/false Formatting techniques

When I pass a dict retrieved from MySQL directly into JSON, the boolean values fail to parse with the error message: 'Current token (VALUE_NUMBER_INT) not of boolean type I'm wondering if casting a TINYINT(1) to a JavaScript boolean using thi ...