I possess a JSON array object and need to identify and extract the array objects that contain a specific child node

const jsonArray = {
     "squadName": "Super hero squad",
     "homeTown": "Metro City",
     "formed": 2016,
     "secretBase": "Super tower",
     "active": true,
     "members": [
      {
      "name": "Molecule Man",
      "age": 29,
      "secretIdentity": "Dan Jukes",
      "powers": [
        "Radiation resistance",
        "Turning tiny",
        "Radiation blast"
     ]
   },
   {
    "name": "Madame Uppercut",
    "age": 39,
    "secretIdentity": "Jane Wilson",
    "powers": [
      "Million tonne punch",
      "Damage resistance",
      "Superhuman reflexes"
     ]
    },
    {
     "name": "Eternal Flame",
     "age": 1000000,
     "secretIdentity": "Unknown",
     "powers": [
       "Immortality",
       "Heat Immunity",
       "Inferno",
       "Teleportation",
       "Interdimensional travel"
      ]
     }
    ]
   }

The JSON array object above contains details of a super hero squad. I'm trying to filter out the member named "Eternal Flame" and retrieve their information.

I need help in correctly returning the data for the specific member, as I am having trouble with my current approach. Any assistance would be greatly appreciated. Thank you in advance.

{
     "squadName": "Super hero squad",
     "homeTown": "Metro City",
     "formed": 2016,
     "secretBase": "Super tower",
     "active": true,
     "members": [
     {
      "name": "Eternal Flame",
      "age": 1000000,
      "secretIdentity": "Unknown",
      "powers": [
       "Immortality",
       "Heat Immunity",
       "Inferno",
       "Teleportation",
       "Interdimensional travel"
      ]
     }
    ]
   }
jsonArray.map(member => member.members.forEach(details => {
     const newArray = [];
     if (details.name === 'Eternal Flame') {
       return ***memberDetails***;
     } else return null;}))

Answer №1

First and foremost, the JSON structure you provided appears to be invalid.

Let's assume that the jsonArray represents a squad object containing members, and you are looking for a member with the name Eternal Flame.

Furthermore, your current code will result in an array of the same length as the members array, filled with null values except for the matching node. To retrieve only the matching node (i.e., member)...

jsonArray.members.filter(member => member.name === "Eternal Flame") [0]; // [0] Retrieves the first matching item from the array (Should only have one match)

Answer №2

Assuming that the name of each member is unique, you can utilize the following code snippet:

const newJson = {
  ...jsonArray,
  members: [jsonArray.members.find(member =>  member.name === "Eternal Flame")]
}

This method initially incorporates the data from jsonArray into a new variable called newJson, and then assigns the members property of newJson to an array that includes only the specific member being searched for.

If the name is not unique, you can modify the code as follows:

const newJson = {
  ...jsonArray,
  members: jsonArray.members.filter(member =>  member.name === "Eternal Flame")
}

When using your own data, in both scenarios, the resulting output will be:

{
   "squadName": "Super hero squad",
   "homeTown": "Metro City",
   "formed": 2016,
   "secretBase": "Super tower",
   "active": true,
   "members": [
      {
         "name": "Eternal Flame",
         "age": 1000000,
         "secretIdentity": "Unknown",
         "powers": [
            "Immortality",
            "Heat Immunity",
            "Inferno",
            "Teleportation",
            "Interdimensional travel"
         ]
      }
   ]
}

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

HTML code for adding a dropdown menu inside a table cell

I am trying to set up a table where one cell functions as a dropdown menu. The data.field is being fetched from the backend and I want it to be displayed during rendering. Additionally, a fList is also retrieved from the backend. When a user clicks on th ...

Guidelines for callbacks and the impact on scope

I am currently diving into the world of scopes in angularjs, specifically when it involves calling callbacks on the module utilizing a directive. I have discovered three different methods to achieve the same goal and I am attempting to comprehend the advan ...

Submitting an image from React and Redux to the backend: A comprehensive guide

I'm currently working with the MERN stack and facing an issue while trying to upload an image in the front end (react) and then access it in the backend (express, nodejs) for later storage. Despite using multer, I keep encountering 'undefined&apo ...

Does the class effectively implement the interface even if the method of a member variable has undefined arguments?

Let's take a closer look at my code, which lacks proper descriptions. Here is the interface: interface IModel<T = any> { effects: { [key: string]: (getState: () => T) => void; }; } interface IState { name: string; age: numbe ...

Navigate to a specific URL path and send properties as arguments in the function for handling events

I am working on a vuetify autocomplete search feature. When a user selects an item, I need to navigate to a specific route and pass some props along. However, my attempts to change the current route without passing props have resulted in errors. Here is w ...

Tips for resolving the issue of 'no serverless pages built' during deployment of a Next.js application on Vercel

Recently, I've been encountering the same two errors while trying to deploy my NextJs app: // and will just error later on Error: No serverless pages were built. You can learn more about this error here I'm stuck and unsure of how to resolve bo ...

What is the best way to integrate ES6 ReactJS code into an Express application?

I am trying to initially render my ReactJS application on the server using ExpressJS. Although I have been able to import ES6 modules using require(), the module crashes upon loading because it contains ES6 code (ES6 import and export). Index Route var ...

Difficulty encountered when applying a CSS class with JavaScript

The Javascript function I am currently using is able to select multiple links. This behavior occurs because of the Regular expression I applied with the '^' symbol. I decided to use this approach because my links are in the following format: htt ...

Execute the function within setInterval only one time

I have a setInterval function that calculates the time difference between a specified date and the current time. Once this difference is less than an hour, I want to execute some code only once. const countdownDate = new Date('March 15, 2021 11:30:00& ...

What is the best way to retrieve the Hash value of an object in Typescript?

What is the process for obtaining the hash value of an object in typescript? For instance: let user:any = {name:'tempuser', age:'29'}; let anotheruser:any = {name:'iam', age:'29'}; if( Object.GetHashCode(user) === ...

retrieving an array of checkbox values using AngularJS

As a beginner in Angular, I have been struggling to implement a feature where I can add a new income with tags. I have looked at similar questions posted by others but I still can't get it to work. The tags that I need to use are retrieved from a ser ...

AngularJS 500 server error

In my current project, I am developing a straightforward angularjs - J2EE application that fetches data from a mysql server and then displays it on an HTML page. The angular function is triggered on form submission as shown below: <div id="register_for ...

Pressing the button will allow you to select and copy the text within the

I am looking to incorporate a mock-chat feature into my website. The concept is to type something on the website, then click a button next to it which will move the text to a frame above. I attempted this using a textarea and even found a code for selectin ...

What is the best way to include numerous optional parameters within a single route in Express?

Been a huge fan of Stackoverflow and finally decided to ask my first question here! I've been working on a JavaScript Express project, trying to figure out if it's possible to achieve the desired functionality under a single GET request. Struggli ...

Issue encountered while deploying Firebase Functions: Unable to parse function triggers

Experiencing difficulty deploying firebase functions from an angular project after updating to the latest firebase-tools 7.8.1 version. The project's package.json contains "firebase-admin": "~6.0.0", "firebase-functions": "^2.1.0", and "firebase-funct ...

Adhering button for sliding side panel

Check out my JSFiddle HERE to see what I have done. I would really appreciate it if someone could help me figure out how to make the show button float with the sidr panel :) <style type="text/css"> #panel { position: fixed; top: 50%; r ...

Tips for customizing the color of the current date in the angular-material datepicker

I've created a function in angular-material to disable dates two days from now, but I'm struggling to change the color of the current date if it's disabled. The issue is that when the current date is disabled, it displays in a very light blu ...

Invoking Javascript Functions using their names

Suppose I have the following element on my page... <span data-function="DoSomething">Click</span> ... and then add the following to my page header... $(document).ready(function() { $('[data-function]').each(function() { ...

Having trouble with sending an AJAX request to a different domain?

I've been attempting to utilize the following API: However, upon making an AJAX call, I encounter this specific error: XMLHttpRequest cannot load /radius.json/30341/10/mile. No 'Access-Control-Allow-Origin' header is present on ...

Having trouble getting unique input values to pass through ajax

For the past couple of weeks, I've been searching for a solution to my issue. The problem arises in my PHP foreach loop where I have div tags representing rows of data fetched from the database. Each div row contains HTML input elements and a button t ...