Verify if the keys are present within the object and also confirm if they contain a value

How can we verify keys and compare them to the data object? If one or more keys from the keys array do not exist in the object data, or if a key exists but its value is empty, null, or undefined, then return false; otherwise, return true.

For example, if the keys include 'summary' and it exists in the object data but the value is empty, the result should be false;

I have attempted using Object.keys and includes but haven't been able to figure it out. Perhaps someone has a solution. Thank you.

#currentCode

 const sample =  Object.entries(sampleOject).some((value) => {
          return keys.includes(value[0]) ? false : (value[1] === null || value[1] === "");
      })

Thank you.

#keys

const keys =  [
    'summary',
    'targetRecdate',
    'majorPositiveAttributes',
    'generalRealEstateConcernsorChallenges',
    'terminationPayment',
    'effectiveDate',
    'brokerCommission',
    'brokerRebate',
    'netEffectiveBrokerCommission']

#sample object data

{
    "dealDispositionType": "A",
    "majorPositiveAttributes": "a",
    "terminationPayment": "31",
    "netEffectiveBrokerCommission": -12189,
    "brokerCommission": "123",
    "brokerRebate": "12312",
    "isPharmacyRestriction": 0,
    "periodOfRestriction": null,
    "pharmacyRestrictionDate": null,
    "targetRecdate": "2022-10-20",
    "isLandLordConsent": false,
    "summary": ""
}

Answer №1

To validate if all keys in an array are present and not empty in a given object, you can utilize the every() method along with hasOwnProperty and additional checks for empty strings.

const result = keys.every(key => {
    return data.hasOwnProperty(key) && data[key] !== ''
}, {});

const keys =  [
    'summary',
    'targetRecdate',
    'majorPositiveAttributes',
    'generalRealEstateConcernsorChallenges',
    'terminationPayment',
    'effectiveDate',
    'brokerCommission',
    'brokerRebate',
    'netEffectiveBrokerCommission'
];

const data = {
    "dealDispositionType": "A",
    "majorPositiveAttributes": "a",
    "terminationPayment": "31",
    "netEffectiveBrokerCommission": -12189,
    "brokerCommission": "123",
    "brokerRebate": "12312",
    "isPharmacyRestriction": 0,
    "periodOfRestriction": null,
    "pharmacyRestrictionDate": null,
    "targetRecdate": "2022-10-20",
    "isLandLordConsent": false,
    "summary": ""
};

const result = keys.every(key => {
    return data.hasOwnProperty(key) && data[key] !== ''
}, {});

console.log(result); // False

Answer №2

Your code has been successfully optimized.

const data =  Object.entries(jsonObject).map(([k, v]) => {
   return keys.includes(k) ? v ? true : false : false;
})

...

const keys =  [
'summary',
'targetRecdate',
'majorPositiveAttributes',
'generalRealEstateConcernsorChallenges',
'terminationPayment',
'effectiveDate',
'brokerCommission',
'brokerRebate',
'netEffectiveBrokerCommission']

const object = {
    "dealDispositionType": "A",
    "majorPositiveAttributes": "a",
    "terminationPayment": "31",
    "netEffectiveBrokerCommission": -12189,
    "brokerCommission": "123",
    "brokerRebate": "12312",
    "isPharmacyRestriction": 0,
    "periodOfRestriction": null,
    "pharmacyRestrictionDate": null,
    "targetRecdate": "2022-10-20",
    "isLandLordConsent": false,
    "summary": "test"
}

let array = [];

const output = Object.entries(object).map(([key, value]) => {
    if (keys.includes(key)) {
        if ((value !== '') && (value !== 'undefined') && (value !== 'null')) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
})

const finalValue = output.includes(true);

console.log(finalValue)

Answer №3

To verify the presence of all keys in the data variable, I suggest utilizing the .every method.

Furthermore, by using non-strict !=, you can determine if a certain key does not contain either null or undefined.

const keys =  [
    'summary',
    'targetRecdate',
    'majorPositiveAttributes',
    'generalRealEstateConcernsorChallenges',
    'terminationPayment',
    'effectiveDate',
    'brokerCommission',
    'brokerRebate',
    'netEffectiveBrokerCommission'];
const data = {
    "dealDispositionType": "A",
    "majorPositiveAttributes": "a",
    "terminationPayment": "31",
    "netEffectiveBrokerCommission": -12189,
    "brokerCommission": "123",
    "brokerRebate": "12312",
    "isPharmacyRestriction": 0,
    "periodOfRestriction": null,
    "pharmacyRestrictionDate": null,
    "targetRecdate": "2022-10-20",
    "isLandLordConsent": false,
    "summary": ""
};

const check = (obj, keys) => keys.every((key) =>  
    key in obj && obj[key] != undefined);

console.log(check(data, keys));

Answer №4

Based on the information from mdn:

let person = { name: 'Alice', age: 25, job: 'Engineer' };
console.log('age' in person); // output will be: true

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

Add a CSS class to the text that is selected within a Content Editable div

Hey there, I'm having an issue where the class is being applied to the button when pressed instead of the selected text. Here's my current code: The button needs to be a div, but it might be causing the problem. I just want the highlighted text ...

Repetitive series of HTTP requests within a looping structure

Within my AngularJS project, I encounter the need to execute a varying number of HTTP requests in sequence. To achieve this, I believe that utilizing a loop is necessary: for (let i = 0; i < $scope.entities.length; i++) { MyService.createFixedValue ...

Limit the frequency of function calls in Typescript

Update: After some research, I've learned that throttle has the capability to drop excess function invocations, making it unsuitable for my needs. I am still seeking an idiomatic solution to process every item in a queue at an appropriate pace without ...

Utilizing jQuery or JavaScript to transfer information within a Bootstrap modal

I am working with a table that is generated from an SQL Table using PHP for data looping. HTML <tbody> <?php $no = 1; foreach($data_request as $data) { ?> <tr> <td class="center"><?php echo $no++.". ";?> ...

Passing JSON data with special characters like the @ symbol to props in React can be achieved

Using axios in React, I am fetching JSON data from a database. I have successfully retrieved the JSON data and stored it in state to pass as props to child components within my application. However, the issue arises when some of the objects in the JSON s ...

Sharing application state between different routes in React Router v4 can be achieved by using methods such

I'm seeking solutions to address the following challenge: Without utilizing any state management library, I solely rely on React. The primary application state is contained within the <MyFoodApp/> component, which includes an array of restaura ...

toggle the class on a label that contains a checkbox

Is there a way to use toggleClass to add a class to a label when clicked, even if the label contains a checkbox? Currently, I am having an issue where the class is only added when clicking directly on the checkbox. How can I make it so that the class is ad ...

Loading external scripts prior to component loading in Vue.js

Within my Vue project, I have the need to fetch a script from a server location (e.g. https://myurl.com/API.js). This script contains a variable that I intend to utilize within my Vue component/view. The issue arises when I attempt to load this script usi ...

Choose an option from a dropdown menu using JavaScript

Currently, I am working on a project that involves using javascrypt in conjunction with selenium. While attempting to search for and select an item from a list, I have encountered difficulties in selecting the element even after successfully locating it. I ...

What is the best way to exchange the chosen selection within 2 select elements?

I have been trying to swap the cities in my select fields using two select elements, but for some reason, it is not working when the button is clicked: <div class="select-wrapper"> <select class="airport-select__departure"> <o ...

Creating randomized sequences using JavaScript

One of my hobbies involves organizing an online ice hockey game league where teams from different conferences compete. It's important to me that every team gets an equal number of home and away matches throughout the season. To simplify this task, I&a ...

Integrate ThreeJs models into an Angular JS application

I have a question that pertains to my webapp development. I am currently utilizing Angular Js (v1.5/1.6) and I would like to incorporate some minimalistic 3D animated models by integrating Three Js. Although I have attempted to configure certain aspects, ...

Instructions for passing a JavaScript variable to a PHP MySQL database

I am attempting to integrate a JavaScript variable into PHP MySQL, but I'm encountering issues with the insertion. Currently, it is being inserted as <javascript>document.write(window.outerWidth); </javascript> x <javascript>document ...

Pressing the reset button will restore the table to its original

As a new React developer with experience mainly in hooks, I have been struggling to find a good example involving hooks. Currently, I am working on implementing an antd table with search functionality. My question is, when a user types something into the ...

transfer chosen data from a text box to a dropdown menu

Looking for: I am in need of a feature where users can input a movie title in a textbox and upon clicking the "move to selectedlist" button, the entered movie title should be added to a dropdown list that displays all the movies selected by the user. Addit ...

Storing row details in Vue.js based on selected options from a dropdown menu

Displayed below is my code that generates a dynamic table. I am looking to save specific rows based on the selection made from a dropdown menu and then clicking on an update button. <b-field> <b-select name="contacted" id="" ...

Nestjs is throwing an UnhandledPromiseRejectionWarning due to a TypeError saying that the function this.flushLogs is not recognized

Looking to dive into the world of microservices using kafka and nestjs, but encountering an error message like the one below: [Nest] 61226 - 07/18/2021, 12:12:16 PM [NestFactory] Starting Nest application... [Nest] 61226 - 07/18/2021, 12:12:16 PM [ ...

Guide to loading an image and incorporating it into a canvas using Gatsby's server-side rendering

I encountered an issue where I was unable to create an image using any of the supported types like CSSImageValue, HTMLImageElement, SVGImageElement, HTMLVideoElement, HTMLCanvasElement, ImageBitmap, or OffscreenCanvas in my SSR application with Gatsby. De ...

What steps should I take to incorporate this feature into my Meteor project?

After successfully installing the type.js package, I discovered that the code works fine when directly executed in the console. Here is the code snippet: $(function(){ $(".typedelement").typed({ strings: ["You don&apo ...

Utilizing Angular to intercept AJAX requests, verifying internet connectivity before proceeding with sending the request

In my Angular (with Ionic) app, I have this code snippet: my_app.factory('connectivityInterceptorService', ['$q', '$rootScope', function ($q, $rootScope) { var connectivityInterceptorServiceFactory = {}; var _request ...