Unlock the secrets of filtering a JSON array object with nested SQL Query-like precision using ES6 syntax for maximum efficiency

As someone new to ES6 syntax, I could use some assistance with this task.

I have a JSON array structured like so:

var data = [{
    "recordid": 1,
    "recordidclass": "Parent Class",
    "relatedrecid": 2,
    "relatedrecclass": "Child Class2"   
},
{
    "recordid": 1,
    "recordidclass": "Parent Class",
    "relatedrecid": 3,
    "relatedrecclass": "Child Class3"   
},
{
    "recordid": 9,
    "recordidclass": "Parent Class",
    "relatedrecid": 14,
    "relatedrecclass": "Child Class4"   
},
{
    "recordid": 2,
    "recordidclass": "Parent Class",
    "relatedrecid": 5,
    "relatedrecclass": "Child Class5"   
},
{
    "recordid": 5,
    "recordidclass": "Parent Class",
    "relatedrecid": 6,
    "relatedrecclass": "Child Class6"   
},
{
    "recordid": 3,
    "recordidclass": "Parent Class",
    "relatedrecid": 7,
    "relatedrecclass": "Child Class7"   
},
{
    "recordid": 4,
    "recordidclass": "Parent Class",
    "relatedrecid": 8,
    "relatedrecclass": "Child Class8"   
},{...}]

All parent and child objects are stored within the same array. The goal is to filter the data based on the recordid, retrieving all objects that match the recordid as well as their corresponding relatedrecid objects.

In simple terms, given the sample data, calling getRequiredData(1) (representing the recordid) should return all data entries that have matching recordid values along with their associated relatedrecid values.

The desired output should look like this:

var result = [{
    "recordid": 1,
    "recordidclass": "Parent Class",
    "relatedrecid": 2,
    "relatedrecclass": "Child Class2"   
},
{
    "recordid": 1,
    "recordidclass": "Parent Class",
    "relatedrecid": 3,
    "relatedrecclass": "Child Class3"   
},
{
    "recordid": 2,
    "recordidclass": "Parent Class",
    "relatedrecid": 5,
    "relatedrecclass": "Child Class5"   
},
{
    "recordid": 3,
    "recordidclass": "Parent Class",
    "relatedrecid": 7,
    "relatedrecclass": "Child Class7"   
}]

Answer №1

Utilize array.find to pinpoint the entry with a matching id. Leverage array.filter to identify entries connected to the initial one.

In this instance, I have amalgamated the outcomes of these two operations into a single array.

var data = [{
    "recordid": 1,
    "recordidclass": "Parent Class",
    "relatedrecid": 2,
    "relatedrecclass": "Child Class2"
},
{
    "recordid": 6,
    "recordidclass": "Parent Class",
    "relatedrecid": 8,
    "relatedrecclass": "Child Class8"
},
{
    "recordid": 9,
    "recordidclass": "Parent Class",
    "relatedrecid": 12,
    "relatedrecclass": "Child Class12"
},
{
    "recordid": 10,
    "recordidclass": "Parent Class",
    "relatedrecid": 14,
    "relatedrecclass": "Child Class14"
}];
          
var someId = 6;
var d1 = data.find(e => e.recordid == someId);
var d2 = data.filter(e => e.recordid == d1.relatedrecid);
d2.unshift(d1);
console.log(d2);

Answer №2

One way to refine your array is by using a filter. More information on this method can be found at:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

To implement this, you can use the following code snippet:

filteredResults = result.filter(function(item){return item.recordId == paramId});

Alternatively, you can stick to the traditional for loop approach which never disappoints.

Roman also highlights that with es6 syntax, you can achieve the same outcome as follows:

filteredResults = result.filter(item=>item.recordId == paramId);

This accomplishes the exact same task in a more concise manner :)

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 method for waiting on a JavaScript function to provide a response utilizing the Chrome.storage API?

I am attempting to utilize the given code for managing name value pairs in a Chrome Extension. if (!this.Chrome_getValue || (this.Chrome_getValue.toString && this.Chrome_getValue.toString().indexOf("not supported") > -1)) { this.Chrome_getV ...

Why does the address bar show value changes in IE when using window.location.hash, but the value doesn't change in the DOM when going

Here is a sample JavaScript code that attempts to detect the back button event: document.location.hash="#1"; document.location.hash="#2"; document.location.hash="#3"; function check() { if("#3"!=window.location.hash) { alert("Back button clic ...

What steps should I take to solve this wheel-related issue in my Vue 3 application?

I have been developing a Single Page Application (SPA) using Vue 3, TypeScript, and The Movie Database (TMDB). Currently, I am tackling the implementation of a search feature and I've encountered a bug. The "search-box" component is located in src&b ...

Unable to locate the accurate information

Every time I run the cycle, there should be a match with the specified parameters and the message "OK" should appear. However, I am always getting a result of "No". request( { url: 'http://localhost:5000/positions/get', metho ...

Preventing page navigation in JavaScript: Why it's so challenging

I am encountering an issue with a link element that I have bound a click event to (specifically, all links of a certain class). Below is an example of the link element in question: <a id="2" class="paginationclick" style="cursor: pointer;" href=""> ...

A guide to navigating a JSON array

Utilizing node js, I have extracted the following array by parsing through multiple json files to find a specific value. My json files consist of a collection of IDs with their respective status: isAvailable or undefined. https://i.sstatic.net/AlpVk.png ...

"Enhance Your Smart Contract Interaction with Algrand's Method Calling

Currently, I am working on integrating an Algorand smart contract with a Next.js application. To sign transactions, I am utilizing Pera wallet. However, I have encountered an issue when attempting to call methods from the contract on the front end using th ...

Using JQuery and Javascript to retrieve information from one drop down list based on the selection made in another drop down

I'm currently working on a project that involves 2 drop-down menus. The first menu allows you to select a general model, while the second menu displays specific models based on your selection. http://jsfiddle.net/QskM9/ Here's an example of how ...

Can a dynamic field name be incorporated into a JavaScript Object?

My goal is to dynamically add a field name and update the value based on that. In my situation, the eventType can have 4 types: delivery, send, open, click. However, when I implement this code, I am only getting the eventType as a string. const event = J ...

Placing jQuery in the lower part of my HTML templates lacks adaptability

Lately, I've been optimizing my templates by placing the jQuery code link at the end of the template files to ensure fast page load speeds. Along with that, I have specific javascript modules reserved for certain pages that are included within the con ...

Is it feasible to bypass the dialog box on beforeunload?

Currently, I am utilizing jQuery's bind method like so: $(window).bind('beforeunload', function() { //my code return ""; } In Mozilla Firefox and IE8, everything works smoothly without including the "return "";" statement. No pesk ...

React fails to recognize the key prop

When creating a list of TSX elements, I utilized the following code: this.productsModel = this.state.products.map(o => ( <Grid.Column key> However, I encountered a warning from React: Warning: Each child in a list should have ...

Error: Attempting to access the 'body' property of an undefined object following a POST request in a MEAN application

Currently, I am attempting to send POST data from AngularJS to Express. My approach involves using curl to transmit the POST content. After sending the data and receiving a 200 response, I encounter an issue when trying to access the data through body-par ...

Error: Unable to access null properties while attempting to address Readonly property error by implementing an interface

Here is the code snippet I am working with: interface State { backgroundColor: boolean; isLoading: boolean; errorOccured: boolean; acknowledgment: string; } export class GoodIntention extends React.Component<Props, State> { ... onCli ...

In PHP, you can customize the colors to emphasize different data sets

In my MySQL database connected through PHP, I have data displayed in table format. My goal is to highlight certain data based on age with two conditions: Condition 1: - Color red (#FF7676) for ages greater than 24 Condition 2: - Color yellow (#F8FF00) fo ...

Guide on sending a sizable item as a string utilizing Axios

In order to efficiently save a large and complex object as a JSON file on the server without needing to map it to an object in C# first, I am facing some challenges. Sometimes, when posting the object as a string, the data gets corrupted leading to errors ...

Transform a 2-dimensional array into Leaflet.js markers

Hey there, I'm currently facing an issue with generating markers using leaflet js. I have an object that includes multiple entries for each year, and my goal is to create a layer group for each year that can be toggled on and off. However, I've e ...

What are some methods for altering ReadOnly values?

I am encountering an issue with the value fetchOptions: Readonly<HttpFetchOptionsWithPath> and my attempt to overwrite one of its properties. Here is the method I have tried: ((fetchOptions as Writable<HttpFetchOptionsWithPath>).headers as Wr ...

Guidance needed for integrating WCF service into AJAX web application for sending JSON data

Setting up an ASPX page to call a WCF servcie thorugh a ScriptManager is causing an error when calling the "SpinStitch.Services.Chat.IChatter.CreateChatSession" method. The error message received is "'The server method 'CreateChatSession' fa ...

Unlocking Iframe Mode in CKEditor 4

I've encountered a difference between CKEditor 3 and CKEditor 4. In CKEditor 3, when I call the method CKEDITOR.replace('#textAreaId'), it wraps the editor in an iframe. However, in CKEditor 4, when I call the same method (not inline), the i ...