Verify if the nested JSON object includes a specific key

Currently, I am grappling with a dilemma on how to determine if within a deeply nested JSON object, featuring numerous unknown arrays and properties, lies a specific property that goes by the name "isInvalid". My objective is to identify this property and, if its value is true, return false.

var checkValidity = function (data) {
    for (var property in data) {
        if (data.hasOwnProperty(property)) {
            if (property == "isInvalid" && data[property] === true) {
                return false;
            }
            else {
                if (typeof data[property] === "object" && data[property] !== null) {
                    this.checkValidity(data[property]);
                }
            }
        }
    }
};

The code snippet provided above is what I have been experimenting with, but unfortunately, it has not yielded the expected results. I did attempt to explore the capabilities of underscore as well, but couldn't locate the necessary functions. Does anyone have any suggestions or ideas? (Please refrain from suggesting regular expressions)

Answer №1

If you're specifically looking to verify the presence of a property within JSON without considering its exact location, the quickest and simplest method is to perform a substring search within the original JSON string. As long as the JSON is properly formatted, the property should be represented as '"isInvalid":true'.

var validateProperty = function (jsonString) {
    return jsonString.indexOf('"isInvalid":true') >= 0;
}

Answer №2

You can verify it like so:

var obj = {a:'1',b:'2'};

if(Object.getOwnPropertyNames(obj).indexOf('a') != -1){
console.log('The key "a" is available');
}else{
  console.log('The key "a" is not available');
};

Updating the answer... UPDATE

var obj = {
  a1: '1',
  b: '2',
  c: {
    a: '11'
  }
};
var checkKeyValidity = function (data) {
  if (Object.getOwnPropertyNames(data).indexOf('a') !== -1) {
    console.log('Found the key "a"!!!');
  } else {
    for (var property in data) {

      if (Object.getOwnPropertyNames(property).indexOf('a') !== -1) {
         console.log('Found the key "a"!!!');

      } else {
        if (typeof data[property] === 'object' && data[property] !== null) {
          console.log('Key not found, continue searching within inner object..');
          this.checkKeyValidity(data[property]);
        }
      }
    }
  };
};
checkKeyValidity(obj);

Answer №3

It examines the property isInvalid at each level of nesting to verify its status, and then proceeds to check all other properties within the object. Array#every terminates if any evaluation results in false.

function validateData(data) {
    return !data.isInvalid && Object.keys(data).every(function (property) {
        if (typeof data[property] === "object" && data[property] !== null) {
            return validateData(data[property]);
        }
        return true;
    });
}

var data = {
    a: 1,
    b: 2,
    c: {
        isInvalid: true,
        a: false
    }
};

document.write('validateData() should be false: ' + validateData(data) + '<br>');
data.c.isInvalid = false;
document.write('validateData() should be true: ' + validateData(data));

Answer №4

When dealing with complex JSON search operations, I recommend utilizing jsonpath ( ), as it serves as the JSON version of xpath.

If you need to locate the isInvalid field within the JSON data regardless of its location, you can use the following code snippet:

jsonPath(data, "$..isInvalid")

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

PHP issue with retrieving Facebook page information using file_get_contents

Looking for assistance with retrieving a list of Facebook pages using this code: $graph_url_pages = "https://graph.facebook.com/me/accounts?access_token=".$_SESSION['token']; $pagedata=file_get_contents($graph_url_pages); echo "DATA : <br> ...

Tips for iterating through the properties of every object within a Knockout observableArray and dynamically generating a table

My observableArray is dynamically populated with SQL data, resulting in varying columns each time. I am trying to present the SQL results in an HTML table but facing issues with the code below. This is the desired output format... var viewModel = func ...

What is the best way to reset react-id-swiper every time an event handler is triggered in a React application?

I have incorporated the react-id-swiper module into my React project to create a dynamic image slider. By setting onClick event handlers on buttons with different id attributes, I trigger API calls that update the state and populate the ImageSlider compone ...

AngularJS is throwing an error because it is unable to access the property `$valid` on an undefined object

I am currently working on a web application using AngularJS and I have created the following form: <form name="form2" novalidate><multiselect class="input-xlarge" multiple="true" ng-model="selectedCar" options="c.name for c in cars" change="selec ...

Modifying the file name during the download process using AngularJS

Looking for a solution to download a file from an ajax GET request in angularjs? Currently, I am using an invisible iframe to trigger the "Save as" popup for the downloaded file. However, I need to change the name of the file before the popup appears. If ...

Is there a regular expression that can identify whether a string is included in a numbered list?

Struggling with creating a regular expression to determine if a string is part of a numbered list like those in word processors. Need it to return true only if the string starts with a number, followed by a full stop and a space. Easy for single or doubl ...

A guide on using jCrop to resize images to maintain aspect ratio

Utilizing Jcrop to resize an image with a 1:1 aspect ratio has been mostly successful, but I've encountered issues when the image is wider. In these cases, I'm unable to select the entire image. How can I ensure that I am able to select the whole ...

Babel continues to encounter issues with async/await syntax, even with all the necessary presets and plugins installed

I am encountering a compiler error while attempting to compile an async/await function using Babel. Below is the function in question: async function login(username, password) { try { const response = await request .post("/api/login") . ...

Converting personal injury claims into configuration maps with the help of jq

Here is my input: { "apiVersion": "apps/v1", "kind": "Deployment", "spec": { "template": { "spec": { "containers": [ { "volum ...

Meteor: Transmitting Session data from the client to the server

Below is the code snippet I am utilizing on the client side to establish the Session variable: Template.download.events({ 'click button': function() { var clientid=Random.id(); UserSession.set("songsearcher", clientid); ...

Using MongoDB to compute the mean value of elements within nested arrays

As a newcomer to MongoDB, I am currently working on developing a function that can calculate the average marks for a student. I have formulated the following document: student = { "id": 123456, "name": "John", "surname": " ...

Unraveling in jQuery

Struggling to properly handle the data being returned by JQuery from an API call. Currently encountering an error in the process. Is it possible to iterate through data using a JQuery loop like this? $.each(data.results, function (i, item) { // attemptin ...

JavaScript popup cannot be shown at this time

I'm encountering an issue with displaying popups using JavaScript. Currently, only the div with class "popup" is being shown. When a user takes action, both popup and popup2 should be displayed but for some reason, it's not working as expected. ...

In my current project, I am implementing a feature in Angular 6 to close a Bootstrap modal once the server successfully receives the necessary data

Here, I am working on creating the content for a CRUD component that saves data as needed. My goal is to make the modal disappear once the data is submitted. <div class="container"> <div class="table-wrapper"> <div class="table-ti ...

There appears to be an issue with the server, as it is reporting a TypeError with the _nextProps.children property not

As a newcomer to coding, this is my first question on the forum. I appreciate your understanding and patience as I navigate through some challenges. I'm currently working on making my NextJS SSR app responsive, but after modifying the index.js and ot ...

Retrieving JSON array from appsettings directly in controller without using Configuration in C#

After conducting a search, I found similar questions with JSON Arrays in the answers using IConfigure in the controller. However, my limitation is that I can only use IConfigure in Startup. In my appsettings.json file, I have this JSON Array: { "Em ...

Avoid excessive clicking on a button that initiates an ajax request to prevent spamming

When using two buttons to adjust the quantity of a product and update the price on a digital receipt via ajax, there is an issue when users spam the buttons. The quantity displayed in the input box does not always match what appears on the receipt. For in ...

Encountering a problem in React when trying to install a color detection library

Hey there, I'm working on a Spotify-clone project where I want to detect the dominant color of an image and use it as the background color. Unfortunately, I've run into some errors while trying to integrate libraries like color-theif, node-vibran ...

Can a linked checkbox be created?

Is it possible to create a switch type button that automatically redirects to a webpage when turned on by clicking a checkbox? I'm working on implementing this feature and would like to know if it's feasible. ...

Do you need to define a schema before querying data with Mongoose?

Is it necessary to adhere to a model with a schema before running any query? And how can one query a database collection without the schema, when referred by the collection name? This scenario is demonstrated in an example query from the Mongoose document ...