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

Tips for exporting data to a JSON file using the Google Play Scraper in NodeJS

Recently, I've been exploring the Google Play Scraper and I'm in need of a complete list of all appIds using NodeJS. The issue I'm facing is that it only outputs to console.log. What I really require is to save this output to JSON and then c ...

Display a free Admob banner within an Ionic 3 application

I have integrated Admob's banner into my Ionic 3 app following the guidelines provided in the Ionic documentation at this link. Below is the code snippet I used for displaying the banner on the homepage: import { Component } from '@angular/core ...

How is it possible for me to retrieve data values directly from a sequelize model?

My question is straightforward - when doing a single select in sequelize, a model is returned. Inspecting this model reveals various options such as dataValues, _prevValues, _change, _options, isNewRecord, and more. What puzzles me is that you can also a ...

Utilize an image in place of text (script type="text/javascript")

The vendor has provided me with some code: <a class="sh_lead_button" href="https://107617.17hats.com/p#/lcf/sfrnrskrvhcncwvnrtwwvhxvzkrvzhsd" onclick="shLeadFormPopup.openForm(event)">FREE Puppies</a> <script type="text/javascript" src="htt ...

Tips for seamlessly incorporating WalletConnect into your decentralized app with the help of web3-react

I have been working on integrating WalletConnect into my project by referring to the documentation provided by web3-react. The configuration settings I am using for the connector are as follows: import { WalletConnectConnector } from '@web3-react/wal ...

Custom Sign-in features in NextJS now direct users to the default form for entering login

I have been working on a web app that requires authentication using NextJS default auth middleware. However, whenever I try to log in, the app redirects me to the default NextJS form component at the URL /api/auth/signin?error=CredentialsSignin. Even thou ...

The MemoizedSelector cannot be assigned to a parameter of type 'string'

Currently, my setup involves Angular 6 and NgRX 6. The reducer implementation I have resembles the following - export interface IFlexBenefitTemplateState { original: IFlexBenefitTemplate; changes: IFlexBenefitTemplate; count: number; loading: boo ...

Tips for creating an HTTP only cookie in NestJS

Currently, I am in the process of incorporating JWT authorization with both an accessToken and refreshToken. The requirement is to store these tokens in HTTP-only cookies. Despite attempting this code snippet, I have encountered an issue where the cookies ...

How Can You Create a Sliding List Animation (Up/Down) Using Angular and Twitter-Bootstrap?

Hey, can you give me a hand with this? :) I'm attempting to create a sleek sliding up and down list in Angular, but I'm struggling to make it work. My CSS skills are not very advanced, so I'm still learning and gave it my best shot: http:// ...

Tips for setting a checkbox as checked based on a value using JQuery

My task is to set the checked status of my checkbox based on a data value. So far, I have been using the following method. $(document).ready(function(){ $('#add').click(function(){ $('#insert').val("Insert"); ...

Tips for adjusting HTML files prior to HTMLOutput in Google Apps Script

I'm looking to make some changes to an HTML file within the doGet() function before it's output in HTMLOut. However, I'm running into an issue with the <?!=include('css').getContent();?> code snippet, as it can't be exec ...

Changing Float Attributes to String in Google Earth Engine

I am trying to export data from Google Earth Engine to my Google Drive. To name the file, I am using information from its data properties which results in 2019.0_1.0. However, I would like the file name to be in a different format - '2019_1'. Bel ...

What is the best approach to integrate a JQuery-powered widget into a Vue.js module for seamless use?

I have a group of colleagues who have started developing a complex web application using Vue.js. They are interested in incorporating some custom widgets I created with JQuery in the past, as re-creating them would be time-consuming and challenging. While ...

Creating a jQuery-powered dynamic select field in Rails 3

After implementing the dynamic select functionality from this example on GitHub (GitHub Link), I successfully integrated dynamic selection for car models in my form for adding a new car. The form now filters car models based on the selected car name, and i ...

How to link Array with Observable in Angular2 Typescript without using .interval()

Is it possible to achieve the same functionality without using the "interval()" method? I would like to link an array to an observable, and update the array as well as have the observable monitor the changes. If this approach is feasible, how can we inco ...

utilizing parent scope in a jQuery function callback

Currently, I am facing an issue concerning a jQuery callback working on a variable that is outside of its scope. To illustrate this problem, consider the code snippet below: $('#myBtn').on('click', function(e) { var num = 1; / ...

Unable to isolate segments of a string

Looking for a way to extract two different IDs from the following string: SPList:6E5F5E0D-0CA4-426C-A523-134BA33369D7?SPWeb:C5DD2ADA-E0C4-4971-961F-233789297FE9: using Javascript. The regular expression being used is : ^SPList\:(?:[0-9A-Za-z\-]+ ...

Is there a way to make my modal appear only when the "New" option is clicked?

Is there a way to make my modal in VueJS open only when I click on the "New" option? <select v-model="input.des" @change="$refs.modalName.openModal()"> <option value="A">A</opt ...

Encountering problems with createMediaElementSource in TypeScript/React when using the Web Audio API

Currently, I am following a Web Audio API tutorial from MDN, but with a twist - I am using TypeScript and React instead of vanilla JavaScript. In my React project created with create-react-app, I am utilizing the useRef hook to reference the audio element ...

Step-by-step guide to implementing onClick functionality within a component

Currently, I am utilizing https://github.com/winhtaikaung/react-tiny-link to showcase posts from various blogs. While I am able to successfully retrieve the previews, I am facing an issue with capturing views count using onClick(). Unfortunately, it appear ...