conditionally remove data from json

Recently, I encountered a JSON object with the following structure:

var js = '{
            "person" : {
                        "firstname" : "Steve",
                        "lastname" : "Smith",
                        "other": [
                                    { 
                                       "age" : "32",
                                       "deceased" : false
                                    },
                                    { 
                                       "age" : "14",
                                       "deceased" : false
                                    },
                                    { 
                                       "age" : "421",
                                       "deceased" : false
                                    }
                                 ]
                       }
         }'

I was able to delete all elements within the "other" array using this code snippet:

var j = JSON.parse(js)
delete j[person.other]

However, my goal is to remove only the node where age equals 14.

The desired outcome would be as follows:

{
            "person" : {
                        "firstname" : "Steve",
                        "lastname" : "Smith",
                        "other": [
                                    { 
                                       "age" : "32",
                                       "deceased" : false
                                    },
                                    { 
                                       "age" : "421",
                                       "deceased" : false
                                    }
                                 ]
                       }
}

In my research, I found that the delete operator (found here) does not offer a conditional statement which could accomplish this task.

Please excuse me if this question seems basic. As a beginner in programming, I am eager to learn.

Thank you for your help.

Answer №1

The optimal strategy here is to refrain from modifying the json directly and instead, create a new one:

const filtered = { ...json, other: json.other.filter(item => item.age !== "14") }

In cases where altering the json is absolutely necessary, you can proceed as follows:

let index = json.other.findIndex(item => item.age === "14")
while (index !== -1) {
  json.other.splice(index, 1)
  index = json.other.findIndex(item => item.age === "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

Struggling to understand Regular Expressions in JavaScript

Looking to implement validation regex on a specific text field, here's an example input: 1364-lqap-10926 This requires a format of 4 digits, dash, 4 letters, dash, and 5 digits (total length must be 15 characters). I attempted using \d{4})-([a ...

jQuery plugin stops functioning properly following the use of the jQuery display block method

In my project, I am exploring the use of divs as tabs with jQuery. Within these divs, I also want to incorporate another jQuery plugin. Currently, I have manually created these div tabs using jQuery and set the default style for second and subsequent divs ...

How to eliminate the gap on the first and last slide in Slick.js when centerMode is enabled and infinite is disabled

When using slick.js with centerMode: true and infinite: false, there is currently an issue where a gap appears on the left side of the first slide, as well as on the right side of the last slide. You can see an example of this behavior at https://jsfiddle. ...

Combining duplicate keys in JSON aggregation using MySQL's many-to-many relationship

I'm facing a challenge with returning a JSON representation of a many-many join. My initial plan was to encode the columns returned in the following unique JSON format { "dog": [ "duke" ], "location": [ &quo ...

An Illustrative Example of Inheritance in Javascript?

I've been searching on various platforms for a straightforward example of inheritance without much luck. The examples I've come across are either too complex, obscure, or just not user-friendly. I have multiple service functions that all share so ...

Display one div and conceal all others

Currently, I am implementing a toggle effect using fadeIn and fadeOut methods upon clicking a button. The JavaScript function I have created for this purpose is as follows: function showHide(divId){ if (document.getElementById(divID).style.display == ...

Struggling for hours with a nested React component that refuses to render

I'm new to the world of react and javascript development and currently encountering an issue with nesting a component. While the Home component is displaying correctly, the testComp is not appearing as expected. I'm feeling quite stuck and would ...

Creating TFRecord files for the COCO dataset

I'm currently working on creating an object detector using the TensorFlow library. My goal is to convert the COCO 2017 dataset into a TFRecord format, but I keep encountering this error message. Traceback (most recent call last): File "/Volumes/EXT ...

Loading files using $scriptjs or any other asynchronous loader allows for seamless integration of external resources

Imagine I have developed an AngularJS application that lazy loads controller files (using $scriptjs) and all dependencies when the user navigates to a specific route. This application consists of 3 routes: A, B, and C. My question is: if the user navigate ...

Message successfully sent despite Ajax failure

Hello everyone, I'm currently facing an issue while trying to send a message using the form craft plugin. The error message that I am encountering is " 504 (Gateway Time-out)" along with some technical details: send @ jquery.js:4 ajax ...

Interfaces and Accessor Methods

Here is my code snippet: interface ICar { brand():string; brand(brand:string):void; } class Car implements ICar { private _brand: string; get brand():string { return this._brand; } set brand(brand:string) { this. ...

"Enhancing user experience with CSS hover effects on dynamically loaded content and mobile devices

I have developed a quiz with 2 answer options for each question. To prevent the questions from loading initially, visitors must click a start button, triggering the questions to load via Ajax. The issue I am facing is that when a question is answered, the ...

Steps to obtain a Json Response post successful data storage in ASP.Net

After creating data, how can I receive a response? I want the response to be displayed when it is saved, maybe in a message box. Is this possible? Below is my controller code for saving: [HttpPost] [ValidateAntiForgeryToken] public async System.T ...

Incorporating local JSON data into HTML: A Step-by-Step

I'm completely new to javascript and the utilization of json. What I want to accomplish is quite straightforward, although I am encountering difficulties. My objective is to create a website consisting of two pages: one that showcases artists and ano ...

Why is my jQuery $.ajax success function not providing any results?

When checking the Network tab in Chrome, I noticed that the correct data (action, username, password) is being sent, but the message is not returning to $('#return_login'). Can anyone spot what might be wrong with my code? Below is the jQuery co ...

Modifying the Readonly Attribute of an ASP.NET Web Application with the Power of JQuery

Check out this snippet of HTML code <td style="width: 4pt;"> </td> <td> <span style="display: inline-block; color: Black; font-family: Arial; font-size: 9pt; font-weight: normal; width: 100pt; vertical-align: top;"> ...

Retrieve the initial image from s3 to load into the file pond

Trying to display the initial image from s3 in vue-file-pond, but encountering a CORS origin policy issue due to Xhr requests being blocked. (Server-side option is not used as images are submitted through the form.) Here is my file pond tag: &l ...

Steps for transforming responseText into JSON format:

After making an XMLHttpRequest, I have received the following JSON response: { "results" : [ { "address_components" : [ { "long_name" : "45", "short_name" : "45", "types" : [ "stre ...

Suggestions for placing a script under the scripts menu in Illustrator CS5.1

My script for Adobe Illustrator CS5.1 is not showing up in the scripts menu despite trying to place it in various directories such as: C:\Program Files\Adobe\Adobe Illustrator CS5.1\Presets\en_GB\Scripts\ C:\Progra ...

Can a link be generated that swaps out the original URL redirect for the following visitor upon clicking?

Can the program be fed with a list of links to automatically redirect to the next URL once clicked? In this setup, each visitor would only see one link and not have access to any other URLs in the chain. Is there a way to make this happen? Any suggestion ...