How can I use a for loop to selectively exclude specific elements in JSON objects within an array?

My goal is to execute the function checkIsObjectEmptyOrNot only when the fields "name", "age", and "class" do not contain null values. In case all these values are null (excluding id and book_id), the function should return false. The filtering process must exclude id and book_id as they always have values from the Laravel backend.

 checkIsObjectEmptyOrNot(object){

        for (var key in object) {
            if (key != 'id' && key != 'book_id' && key != null) {
                break;
                return true;
            }
        }
        return false;
    }

For example, I have a Json array like this:

[
    {
         "id": 1,
         "book_id": 2,
         "name": "myname",
         "age": 25,
         "class":null,
    },
    {
        "id": 2,
        "book_id": 2,
        "name": "myname2",
        "age": 25,
        "class": null,
    },
    {
        "id": 3,
        "book_id": 2,
        "name": "myname3",
        "age": 25,
        "class": 10,
    },
]

Answer №1

If you're looking to filter out items based on certain criteria, you can make use of Array.filter function as shown in the snippet below. It will only return items that meet the specified conditions.

const arr = [
 {
 "id":1,
 "book_id":2,
 "name":"myname",
 "age":25,
 "class":null,
 },
{
 "id":2,
 "book_id":2,
 "name":"myname2",
 "age":25,
 "class":null,
 },
{
 "id":3,
 "book_id":2,
 "name":"myname3",
 "age":25,
 "class":10,
 },
].filter((item)=>{
  return item.name && item.age && item.class
})

console.log(arr);

Alternatively, you can use a custom function like the one provided below to check if specific properties in an object are not null or undefined. This function returns true if all required properties are present and valid.

const arr = [{
    "id": 1,
    "book_id": 2,
    "name": "myname",
    "age": 25,
    "class": null,
  },
  {
    "id": 2,
    "book_id": 2,
    "name": "myname2",
    "age": 25,
    "class": null,
  },
  {
    "id": 3,
    "book_id": 2,
    "name": "myname3",
    "age": 25,
    "class": 10,
  },
]

function checkIsObjectEmptyOrNot(object) {
     for (var key in object) {
        if (key !== 'id' && key !== 'book_id' && object[key] !== null)
            return true;
    }
    return false;
}

console.log(checkIsObjectEmptyOrNot(arr[0]));
console.log(checkIsObjectEmptyOrNot(arr[1]));
console.log(checkIsObjectEmptyOrNot(arr[2]));

This function will evaluate to true only if all the specified properties (name, age, class) are not null, undefined, or false. Otherwise, it will return false.

Hope this explanation helps you in your coding endeavors :)

Answer №2

Consider utilizing the forEach method.

var dataList = [
    {
        "id": 1,
        "book_id": 2,
        "name": "myname",
        "age": 25,
        "class": null
    },
    {
        "id": 2,
        "book_id": 2,
        "name": "myname2",
        "age": 25,
        "class": null
    },
    {
        "id": 3,
        "book_id": 2,
        "name": "myname3",
        "age": 25,
        "class": 10
    }
];
var flag = 0;
dataList.forEach(function(item) {
    for (let [key, value] of Object.entries(item)) {
        if (item[key] !== _id || item[key] !== book_id) {
            if (item[key] !== null) {
                flag = 1;
            }
        }
    }
});

if (flag === 0) {
    checkIsObjectEmptyOrNot();
}

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

Iterate through a file in PHP to load data into an array

I have come across the following code: require("class.XMLHttpRequest.php"); function hot($news){ $url="https://localhost/search.aspx?search=".$news.""; $ajax=new XMLHttpRequest(); $ajax->setRequestHeader("Cookie","Cookie: host"); $ajax->open("GE ...

Managing duplicated data models names

While working on connecting to an extensive online service using JSON in C#, I've noticed that they use the same name with different values and types. This poses a challenge when creating JSON models as different models require different value types. ...

Stop unauthorized direct access to PHP forms and only allow submission through AJAX requests

I have set up a script that sends an email notification whenever someone comments on my Facebook comment box. The script uses FB.event.subscribe to trigger an AJAX call to mail.php on my server, which then sends an email to my address. How can I enhance ...

Attach the document for submission from a different source

Utilizing a jQuery DataTable with the capability of containing multiple rows, each row is populated using a modal. Depending on the selected values, each row may or may not have an attachment. This table is located inside a form. The issue arises when atte ...

Prevent multiple requests on jQuery infinite scrolling

I have implemented pagination on my website where the next page is loaded automatically when the user reaches the bottom of the page. This is achieved by using jQuery's .on('scroll', this.detectScroll()) method which triggers a function to l ...

Golang: The Charm of an Empty Byte Array

When using Golang, zero values are utilized in error scenarios. For example, if a key is not found in a map[int]string, an empty string will be returned. I am currently creating a function that accepts a URL as input and returns the JSON string received a ...

What is the significance of a listener signaling an asynchronous response with a return of true, only to have the communication channel close before the response could be received?

Currently, I am developing a React application that involves the use of various npm modules. One of these modules is a self-built NPM package called modale-react-rm (available at this link). This package serves as a simple modal component that utilizes the ...

Using Jquery to fill a dropdown list with options obtained from a JSON array

After developing a PHP script, I encountered an issue where it returned a JSON array as shown below: var option = '[{"mod":"Width","values":{"field":"A","value":"96}}, {"mod":"Height","values":{"field":"B","value":"33}}]'; Here is a snippet of ...

Twitter-Typeahead is failing to provide any recommendations at the moment

I'm currently implementing twitter-typeahead-rails into my project. The goal is to have suggestions for instances of the "User" model displayed in a drop-down menu as I type in the "#Typeahead" input field. However, when I start typing, nothing seems ...

What is the process behind __doPostback generating a URL on an ASP.NET website?

Can you please check out the following URL: When you select "Exhibitor A to Z" from the dropdown menu and click search, a javascript function is triggered for each link (javascript:__doPostBack('ctl00$MainContent$grdExhList$ctl00$ctl04$lnkExhLink&ap ...

Is evaluating student programmers' code with eval() a security risk?

In this unique Express app setup, I have implemented CodeMirror to provide student programmers with a platform to write code in a more enhanced way than a simple textarea. By utilizing eval() function, I evaluate the code inputted by the students in order ...

When clicking on an HTML link pointing to a cloud, it does not open in the same frame but instead opens in a new window

I am currently working on an HTML5 application that features a screen divided into two parts. The left part of the screen contains a few links, and upon clicking one of these links, the resulting content should open in the right side frame within the same ...

What is the best way to include id="" in a textarea generated using javascript?

Having an issue with my textarea var tex = document.createElement("TEXTAREA"); document.body.appendChild(tex); Does anyone know how I can add a class and id to the textarea or areas? ...

Instructions for enabling the touch slider feature in the Igx carousel component with Angular 6 or higher

Looking to enable the touch slider for Igx carousel using angular 6+? I am trying to implement the igx carousel for image sliding with reference from a stackblitz demo (https://stackblitz.com/edit/github-j6q6ad?file=src%2Fapp%2Fcarousel%2Fcarousel.compone ...

An error-free blank page in Three.JS with a CSS3DRenderer

After implementing the CSS3DRenderer in my code, I am encountering a blank page without any errors. My main focus is to draw a line using the CSS3DRenderer as the rest of my code relies on its functionality. Here is the HTML code snippet: <!DOCTYPE htm ...

The looping function in Vue.js data is not functioning properly

Currently, I am developing a shopping cart system using Laravel session and Vue.js. Below is a snippet of my Vue.js code where I loop through the products and add them to the cart/session on click. <div v-for="product in products"> <div cla ...

Preventing the onClick function from executing by using addEventListener

Upon further investigation, I discovered that a button has an onClick event linked to it: <button id="my-button" onClick={myMethod}> My button </button> In addition to this, a listener has been assigned to the button: const listener = (e) ...

Remove an item from an array of objects based on its value

Within the array of nested objects provided below: [ { "items": [ { "name": "See data", "href": "/data", }, { ...

Transform a previously escaped backslash into an escaping backslash

I am facing a challenge where the backslashes in my server-generated string are escaped, which is causing some issues for me. Here is an example of the string I have: const s = 'text\\n' Due to the escaped backslashes, the intended fu ...

Code a Python script that sends an image to the telegra.ph platform

Despite trying to write the code using requests and some assistance from a Github page, unfortunately, I was unable to achieve success. import sys if len(sys.argv) < 2: print("You must specify a file name.") sys.exit(-1) filePath = sy ...