Remove an item from a complex JSON structure based on the specified name. The function will then return the

Hey there, I'm just starting out with react native and I have an array of objects. My goal is to remove an inner object from this JSON data.

[
  {
    Key: 1,
    exchnageArr: [
      {
        name: ”FX”
      },
      {
        name: ”MK”
      }
    ]
  },
  {
    Key: 2,
    exchnageArr: [
      {
        name: ”CK”
      },
      {
        name: ”DK”
      }
    ]
  }
]

I need to get rid of the {name:"FX"} entry in this JSON data by passing "FX". Unfortunately, my attempted solution hasn't been successful. Can someone help me figure out how to do this?


    const newDatavalues = arr.forEach((item) =>
            item.exchangeArr.forEach((subItem, index) => {
              if (subItem.name === "FX") {
               return item.exchangeArr.splice(index, 1);
           } 
       })
     );

Answer №1

To filter out specific elements from arrays within objects, you can utilize the Array#filter method.

let arr=[{Key:1,exchnageArr:[{name:"FX"},{name:"MK"}]},{Key:2,exchnageArr:[{name:"CK"},{name:"DK"}]};
for (const o of arr)
  o.exchnageArr = o.exchnageArr.filter(x => x.name !== 'FX');
console.log(arr);

Answer №2

You made a small error with the property name exchnageArr, it should be exchangeArr. This mistake was found in your array (JSON).

Here is the corrected JSON:

[
  {
    Key: 1,
    exchangeArr: [
      {
        name: ”FX”
      },
      {
        name: ”MK”
      }
    ]
  },
  {
    Key: 2,
    exchangeArr: [
      {
        name: ”CK”
      },
      {
        name: ”DK”
      }
    ]
  }
]

Your code should work properly now.

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

The JSON.parse() function encountering errors when processing the output of the json_script template tag

I am currently utilizing the template tag json_script as demonstrated in the official Django docs. Below is a snippet of my code: {{rules|json_script:"rules"}} <script lang="javascript"> const rules = JSON.parse(document.getElementById(' ...

Material-UI - Switching thumb styles in a range slider

Looking for a way to style two entities differently on the Material-UI Slider? Entity A as a white circle and Entity B as a red circle? While using data-index can work, there's a flaw when sliding. Is there a better approach? if (data-index === 0) { ...

A decoding error occurred due to the 'charmap' codec being unable to read byte 0x8f at position 7738, as it maps to an undefined character

I'm currently working on a Python program that is supposed to extract dates from a website and save this information into a JSON file. Here's the snippet of the code related to the creation of the JSON file: with open(city+'.json', &apo ...

Clicking on the (x) button element will eliminate the DOM node from a list

https://i.stack.imgur.com/GxVYF.png A value is being dynamically added to my page, and here is the code snippet: function favJobs(data){ number_of_jobs_applied = data.total_bookmarked; $('.bookmark-title').append(number_of_jobs_applied, " ...

Expo Snack shows the error message "package not found in registry" while trying to add an npm package

While working on my project in Expo Snack, I came across an issue with the public npm package mentioned below. The strange thing is that I can access and utilize the package locally within my app without any problems, but when I try to run it through Exp ...

The process of extracting values from an HTML tag using Angular interpolation

I am working on an Angular application that has the following code structure: <p>{{item.content}}</p> The content displayed includes text mixed with an <a> tag containing various attributes like this: <p>You can find the content ...

Encounter a problem while installing node modules

I am facing an issue with my test directory which contains a package.json file: { "name": "test", "version": "0.0.1", "dependencies": { "hem": "~0.1.6", } } Upon trying to run node install, I encounter the following error: module.js:337 ...

Horizontal scroll box content is being truncated

I've been trying to insert code into my HTML using JavaScript, but I'm facing a problem where the code is getting truncated or cut off. Here's the snippet of code causing the issue: function feedbackDiv(feedback_id, feedback_title, feedb ...

Change the position of an array element when displayed on an HTML page

I'm trying to figure out a way to manipulate the position of an HTML element that is stored inside an array. The issue I am facing is that my code generates a new div every time a specific function is called, and this div has a class applied to it for ...

Understanding JavaScript Regular Expressions

To ensure that no HTML tags are entered into a textarea, I am utilizing the following regex for validation. If any HTML tags are detected in the textarea, I need to display a validation message. The regex being used is: /<(\w+)((?:\s+\w ...

Include an external JavaScript file within a component to display pictures in a web browser using Angular 2

I am developing a website using Angular 2 and need to incorporate a JavaScript file into a component. The goal is for this script to adjust the height of certain images to match the height of the browser window. What is the best way to integrate this scri ...

Using Javascript or Jquery, you can submit a form without the need for a button

I'm attempting to submit a form without using a button by invoking a JavaScript function and processing the form with JQUERY/PHP. My goal is for the form to be submitted silently on the backend without causing the page to reload. However, I keep encou ...

Error message: The 'target' property cannot be read because it is undefined - react

←→1 out of 3 errors found on the page Error: The property 'target' is undefined and cannot be read This error occurred in the following section: App.inputChangeHandler src/App.js:37 34 | 35 | inputChangeHandler(index,event){ 36 | ...

Navigate to the element by clicking on the link, then apply a class to that specific element

I'm currently working with this HTML code: <div id="main"> <p>some text</p> <a id="goto-notes" href="#">see notes</a> <p>some text...</p> <div id="notes"> <p>notes here< ...

Is there a way to set a personalized callback function when closing a modal with MicroModal?

I've been utilizing MicroModal for showcasing a modal window. Everything seems to be working smoothly, except for when I try to trigger an event upon closing the modal. It's unclear to me where exactly I should implement this callback function. ...

Ways to display a price near a whole number without using decimal points

Currently, I am working on an ecommerce project where the regular price of an item is $549. With a discount of 12.96% applied, the sale price comes down to $477.8496. However, I want the sale price to be displayed as either $477 or $478 for simplicity. Yo ...

What could be causing my Angular Ngrx app's state not to render properly on the application?

Is there a way to automatically render the state when the app loads without having to click a button? I am currently facing an issue where the state is empty until I manually trigger the click function by pressing a button. I have tried using this.store.se ...

I'm seeking an easy method to adjust the x and y coordinates of a popup rectangle with a fixed size. Can anyone provide

Is there a way to create a simple pop-up rectangle, possibly using jQuery or a similar tool, that presents a scaled-down canvas view of a larger browser window (1000px x 1600px), allowing users to click and determine the x/y position within the full window ...

Creating dynamic VueFire references is a powerful feature that allows for more flexibility and customization

I am currently exploring the creation of refs dynamically: The initial ref I created works fine as it is hardcoded, but the second one does not seem to work because it is dynamic: firebase: function(){ return { categories: db.ref('categ ...

Updating the progress bar without the need to refresh the entire page is

Currently, I have two PHP pages: page.php and loader.php. Loader.php retrieves data from MySQL to populate a progress bar, while page.php contains a function that refreshes loader.php every second. This setup gets the job done, but it's not visually a ...