Guide to looping through a JSON object in JavaScript and removing a particular JSON entry depending on a condition

I've already done a thorough search and couldn't find a match, so please don't ask about any copy-pasted solutions before you ask your question. :)

Now, in JavaScript(ES6), I am working with this JSON data:

var myJson = {
   'hello' : {x: 11, y:22},
   'there' : {x:99, y:100}
};

I understand that to delete a row from a JSON object, I can simply use the delete keyword. However, my challenge lies in deleting rows based on a certain condition, such as deleting all rows where the value of X is greater than 50. For example,

delete myJson['there']. 

The issue here is that I do not know beforehand which key will meet this criteria, so using delete directly is not feasible. I have also researched (not confirmed) that looping over this JSON object and accessing the loop index to remove a specific row like in an array would not work due to the structure of objects.

Considering the condition to exclude rows where X > 50, the desired final output should be:

myJson = {
       'hello' : {x: 11, y:22}
    };

Appreciate any insights or suggestions! Thanks!

Answer №1

Check out this solution. The purpose of using the hasOwnProperty method is to verify if the key belongs to the object itself and not its prototype.

var myObject = {
   'hi' : {x: 11, y:22},
   'bye' : {x:99, y:100}
};

for(var property in myObject) {
    if(myObject.hasOwnProperty(property)) {
        if(myObject[property].x > 50) {
            delete myObject[property];
        }
    }
}

console.log(myObject);

I changed the variable name to myObject as it was not in JSON format. To convert the object into JSON, you can use the following code:

var myObject = {
   'hello' : {x: 11, y:22},
   'there' : {x:99, y:100}
};

var myJson = JSON.stringify(myObject);

console.log(myJson);

Answer №2

let sampleObject = {
   'alpha' : {a: 40, b:60},
   'beta' : {a:90, b:120}
};


for( element in sampleObject) {
  if (sampleObject[element].a > 70) {
    delete sampleObject[element];
  }
}

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

Get the value of the button that has been clicked

I have a query regarding building a website that can be started via PowerShell. The PowerShell HTML code I am using is: $proxys = "" foreach ($email in $ADObj.proxyAddresses){ $proxys += "<button id='$email' name='alias&apo ...

"Trouble with Angular JS foreach loop: only the final item in the array

Struggling to loop through each item object in a JSON data set and evaluate its value using angular.forEach(). However, only the last item is being returned, making it impossible to perform any meaningful evaluation. Oddly enough, when using console.log(), ...

JavaScript for Each Method Implementation

While reading a tutorial, I came across a code snippet for a forEach function that all made sense except for the part where it checks if i is in the array: if (i in this) { I'm confused as to why this check is necessary since we already have a s ...

How can Angular HttpClient be used to convert from Http: JSON.parse(JSON.stringify(data))._body?

When using the Http module, you can use this method: Http service: let apiUrl = this.apiUrl + 'login'; let headers = new Headers({'Content-Type': 'application/json'}); return this.http.post(apiUrl, JSON.stringify(model), {h ...

Generate a series of inquiries from an API response and display them dynamically, complete with a text field and radio button for each question

Currently, I am in the process of developing a Question/Answer page using ReactJS. The questions are retrieved through an API call. I aim to present a series of radio buttons and text fields for users to respond to these questions. A "Panel" that resemble ...

Unlock the potential of JavaScript by accessing the local variable values in different functions

I've been struggling for days to find a solution to this issue... https://i.stack.imgur.com/KDN7T.jpg https://i.stack.imgur.com/tOfCl.jpg The image above illustrates the challenge I'm facing - trying to apply data values from elsewhere to the ...

Built-in JSON parser in Java

I've recently encountered a task that involves making a request and extracting the value of a specific key from JSON data. Due to some constraints, I am required to only utilize built-in Java libraries for this purpose. While I have successfully impl ...

Loading dynamically generated div content using AJAX with additional hyperlinks to various files has posed the question of how to seamlessly integrate the content of these links into the original div container

Issue: I am facing a challenge with my webpage setup. The main.jsp page contains a header, left panel, and content divs. When a link in the left panel is clicked, I use a JavaScript Ajax call to populate the content div with new information. This content a ...

Unable to access, manipulate, and view a font file in nodejs

Issue : I encountered a discrepancy when downloading a file using the request module and writing it to the file system compared to directly downloading it using a browser. The file in question is a font located at https://assets.ajio.com/static/assets/ec ...

Unable to differentiate between .jsx and .js files

Here is the content of my JavaScript file: var React = require('react'); export default class AmortizationChart extends React.Component { render() { var items = this.props.data.map(function (year, index) { ret ...

"Proceeding to" express this redirection

Greetings, I am currently struggling to understand why res.redirect('/index') is rendering like this: <p>OK. Redirecting to <a href="/index">/</a></p> Instead of directly redirecting on the page. I searched through th ...

I am having an issue with my jQuery form submission not sending any POST variables

My code seems to be having issues as the PHP file is not receiving the POST-variables. I am unsure of what could be going wrong, so I am reaching out for some guidance. Here is the HTML: <div id="preloader" class="preload"></div> <div id=" ...

Incorporate zoom feature into the jQuery polaroid gallery

Currently, I am utilizing a jQuery and CSS3 photo gallery found on this website. My goal is to allow the images to enlarge when clicked, however, the method provided by the author isn't very clear to me, as I'm not an expert in jQuery. I attempt ...

Nextjs is facing challenges in enhancing LCP specifically for text content

I've been trying to boost my LCP score by optimizing the text on my page, but it seems stuck and I can't figure out why my LCP isn't improving. Take a look at the screenshot: https://i.stack.imgur.com/xfAeL.png The report indicates that &a ...

What is the best way to manage an empty JavaScript object?

I'm feeling stuck. Check out this code snippet: const clientInfoPromise = buildPromiseMethod clientInfoPromise.then((clients) => { console.log('clients ' + JSON.stringify(clients)) console.log(clients.typeOf) console.log(_.k ...

Is it possible to merge several blobs into one zip file using JSzip?

When attempting to download multiple images as a single ZIP file, the result is receiving separate zip files instead. The console log shows that the 'urls[]' array contains different arrays. const fileURLs = window.URL.createObjectURL(result);// ...

What could be causing React to throw an error?

Check out this React Component: GeneralInformation = React.createClass({ totalCaptialRaisedPanel: function() { var offeringInfo = this.props.company.data.offerings.data[0]; var percentageComplete = (offeringInfo.capital_raised / offer ...

Passing a div's ID value using AngularJS AJAX to store it in a PHP variable

I have a collection of div elements, each with a unique id. My goal is to trigger a JavaScript function when a specific div is clicked. This function should send the id value of the clicked div to PHP, assign it to a PHP variable, and then receive a respon ...

Encountering Type Error in Angular 2

Here is the Angular 2 code snippet I am working with: <ion-grid *ngFor="let item of menuData; let i = index;" ng-init="getAllItemToGrid()"> <img src="{{'assets/Products/'+menuData[i].image}}" ng-click="onLogin()" width="100%"> ...

Burger menu animation activated by a single click anywhere on the page

After following a tutorial on creating an animated menu burger, I encountered a few bugs. The animation is working as intended, but it triggers no matter where I click on the page. Here is the code snippet: const toggleMenu = document.querySelector( ...