Validating object keys

I am dealing with an array of objects and I need to find a way to pass multiple keys in the function checkArray to validate these keys within each object.

var test = [
  {
    // Object details here...
  },
  {
    // Another object details here...
  }
];

function isKeyInObject(obj, key) {
  var res = Object.keys(obj).some(v => v == key);
  return res;
}

const checkArray = (test, ...keys) => {
  let valid = true;

  test.map(item => {
    keys.forEach(key => {
      if (!isKeyInObject(item, key)) valid = false;
    });
  });

  return valid;
};

console.log(checkArray(test, 'VAT', 'destination', 'insured_tin'));

Is there a way for me to pass a list of keys instead of just one key for validation? Currently, I can only pass one key at a time. Ideally, I'd like to use something like

checkArray(test, 'VAT', 'destination', 'insured_tin');

Answer №1

You can easily accomplish this by utilizing the every method of Array

var sampleData = [
  {
    date_issued: '2018-05-25',
    transaction_type: 'IMPORT',
    policy_number: '061/100/001052/2018',
    open_cover: false,
    endorsement_number: '',
    icc: 'ICC-A',
    insured_name: 'SAYONA STEEL LTD',
    insured_email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc919590919d8ebc9b919d9590d29f9391">[email protected]</a>',
    insured_tin: '103 286 883',
    intermediary_name: 'MILMAR',
    intermediary_tin: '100-714-078',
    goods_category: 'Mineral Products',
    country_of_origin: 'HK',
    destination: 'Mwanza Region',
    conveyance: 'SEA',
    financier: '',
    currency_code: 'USD',
    exchange_rate_used: '2262.37',
    sum_insured: '23302411',
    premium: '33935.55',
    VAT: '5176.609322',
    unit_of_measure: 'UNITS',
    quantity: '800',
    cover_start_date: '2018-05-15'
  },
  {
    date_issued: '2018-05-25',
    transaction_type: 'IMPORT',
    policy_number: '061/100/001051/2018',
    open_cover: false,
    endorsement_number: '',
    icc: 'ICC-A',
    insured_name: 'URHOME COMPANY LTD',
    insured_email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dbb6b2b7b6baa99bbcb6bab2b7f5b8b4b6">[email protected]</a>',
    insured_tin: '132-209-898',
    intermediary_name: 'MILMAR',
    intermediary_tin: '100-714-078',
    goods_category: 'Base Metals And Articles Of Base Metal',
    country_of_origin: 'CN',
    destination: 'Dar es Salaam Region',
    conveyance: 'SEA',
    financier: '',
    currency_code: 'USD',
    exchange_rate_used: '2262.37',
    sum_insured: '54941202.98',
    premium: '58821.62',
    VAT: '8972.789492',
    unit_of_measure: 'UNITS',
    quantity: '2792',
    cover_start_date: '2018-05-15'
  }
];

const checkKeysExist = (sampleData, keys) => {
  return sampleData.every(item => keys.every(key => item.hasOwnProperty(key)));
};

console.log(checkKeysExist(sampleData, ['VAT', 'currency_code']));
console.log(checkKeysExist(sampleData, ['VAT', 'unknown']));

Answer №2

To check if an object has specific keys in JavaScript, you can easily use the hasOwnProperty() method.

var test = [
  {
    date_issued: '2018-05-25',
    transaction_type: 'IMPORT',
    policy_number: '061/100/001052/2018',
    open_cover: false,
    endorsement_number: '',
    icc: 'ICC-A',
    insured_name: 'SAYONA STEEL LTD',
    insured_email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="563b3f3a3b372416313b373f3a7835393b">[email protected]</a>',
    insured_tin: '103 286 883',
    intermediary_name: 'MILMAR',
    intermediary_tin: '100-714-078',
    goods_category: 'Mineral Products',
    country_of_origin: 'HK',
    destination: 'Mwanza Region',
    conveyance: 'SEA',
    financier: '',
    currency_code: 'USD',
    exchange_rate_used: '2262.37',
    sum_insured: '23302411',
    premium: '33935.55',
    VAT: '5176.609322',
    unit_of_measure: 'UNITS',
    quantity: '800',
    cover_start_date: '2018-05-15'
  },
  {
    date_issued: '2018-05-25',
    transaction_type: 'IMPORT',
    policy_number: '061/100/001051/2018',
    open_cover: false,
    endorsement_number: '',
    icc: 'ICC-A',
    insured_name: 'URHOME COMPANY LTD',
    insured_email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c111510111d0e3c1b111d1510521f1311">[email protected]</a>',
    insured_tin: '132-209-898',
    intermediary_name: 'MILMAR',
    intermediary_tin: '100-714-078',
    goods_category: 'Base Metals And Articles Of Base Metal',
    country_of_origin: 'CN',
    destination: 'Dar es Salaam Region',
    conveyance: 'SEA',
    financier: '',
    currency_code: 'USD',
    exchange_rate_used: '2262.37',
    sum_insured: '54941202.98',
    premium: '58821.62',
    VAT: '8972.789492',
    unit_of_measure: 'UNITS',
    quantity: '2792',
    cover_start_date: '2018-05-15'
  }
];

const checkArray = (test, keys) => {
  let valid = true;
  test.map(object => {
    keys.map(key => {
        if(!object.hasOwnProperty(key)) {
            valid = false;
        }
    });
  });

  return valid;
};

console.log(checkArray(test,['VAT','intermediary_name']));
console.log(checkArray(test,['VAT','intermediary']));

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

"Is there a way to retrieve the props that have been passed down to a

I am looking to have custom props created in the root layer of my React app: import React from 'react' import App, { Container } from 'next/app' export default class MyApp extends App { static async getInitialProps({ Component, rout ...

What is the best way to insert HTML elements onto a webpage and retrieve them in an asp.net environment?

Greetings, For the past day, I've been attempting to dynamically add elements to a web page using Visual Studio and access their values. Either I'm overthinking things, being foolish, or there just isn't a straightforward way to achieve wha ...

Determining in Express.js whether headers have been sent or not

As I develop a library that involves setting headers, I aim to provide a personalized error message in case the headers have already been sent. Rather than simply letting it fail with the default "Can't set headers after they are sent" message from No ...

What is the best way to only buffer specific items from an observable source and emit the rest immediately?

In this scenario, I have a stream of numbers being emitted every second. My goal is to group these numbers into arrays for a duration of 4 seconds, except when the number emitted is divisible by 5, in which case I want it to be emitted immediately without ...

What is the best way to pass the index value of a v-for loop as an argument to a computed property function in Vue?

I'm looking to pass the index value from a v-for loop (inside a path tag) as a parameter to a function stateData(index) defined in a computed property in Vue. I attempted to achieve this using v-model="stateData[index]", but an error is being displaye ...

Transforming a Nestjs string object into JSON data

I need to convert this to JSON format. I attempted to use JSON.parse(), but encountered an error. "{"status":"00","message":"OK","access_token":"2347682423567","customer":{"name":"John Doe","address":"Mr. John Doe 34 Tokai, leaflet. 7999.","util":"Demo Ut ...

What is the best way to align columns after adding or deleting columns in an el-table using Element UI in Vue.js?

Is there a way to develop a table/datagrid using Element UI that allows users to choose which columns are displayed? I've already made an attempt, and you can find it here. I'm also looking for a solution that enables users to adjust the width o ...

The variable is only recognized within the function and not outside of it

Seeking assistance as a newcomer in debugging and implementing code, I have been trying various approaches to pass a base64string into JotForms for generating images in PDF format. Below is the screenshot of the error encountered. View error here The foll ...

Tips for using Jackson to deserialize a JSON file containing changing keys

I have a JSON formatted string with random number keys. { "tasks": { "0": { "key1": "value1" }, "100": { "key1": "value2" } } Is there a way to convert this JSON string into a Java object using the Jackson library? What shou ...

Update the contents of TubeBufferGeometry with a new TubeBufferGeometry directly, avoiding unnecessary memory allocation

I am working with a mesh that is based on a TubeBufferGeometry. In each animation cycle, the path of the TubeBufferGeometry needs to change based on values provided at runtime. To achieve this, I want to update the geometry with a new TubeBufferGeometry ev ...

Unable to reference a property or method in Vue.js and Vuetify due to an issue with the <v-btn-toggle> button causing an error

Just started using vuetify and exploring the <v-btn-toggle> component for the first time. I'm trying to implement a toggle feature to filter my user list based on employee, manager, or admin types... Check out a snippet of my code below: <v ...

jQuery: automatic submission on pressing enter compared to the browser's autocomplete feature

Here is a JavaScript code snippet that automatically submits the form when the user presses the "enter" key: jQuery.fn.installDefaultButton = function() { $('form input, form select').live('keypress', function(e) { if ((e.which && ...

Pricing information is now available on a new link after scraping it from the search bar

After collaborating with some experts, I successfully developed a scraper that is functioning well. The critical line of code looks like this: data = {"partOptionFilter": {"PartNumber": PN.iloc[i, 0], "AlternativeOemId": "17155"}} r = requests.post(&apos ...

Save the environment value within Vue when the app starts up

When working with a basic web app created using VueJS, the application makes an API call that returns an object containing the environment name. For instance: https://appsdev/mysimpleapp/api/environment returns {"applicationName":"My S ...

Preparing my JSON data for visualization on a chart

I have successfully retrieved data using this API, but now I need to transform it into a chart within my react project. As a newcomer to JS and React, I am struggling to create a chart with the JSON data. My objective is to display prices by bedrooms over ...

Using react hooks, I am refreshing the product image by replacing it with the thumbnail image

I'm currently working on an e-commerce platform that resembles Amazon. In the product detail page, I want the right side image to update when I click on a thumbnail image on the left side. The issue I'm facing is that upon first loading, the def ...

Error: The parent container element cannot be edited until the child element has been properly closed

I received a Script Error stating that I am unable to modify the parent container element before the child element is closed. In response, I clicked Yes but my web page isn't being displayed. In the code for my Product page, I start with: http://past ...

Issue with ng-disabled not functioning properly for href tag within list item

Is there a way to prevent clicking on the <a> tag within a list item in a UI list so that the associated <div> is not displayed when clicked (excluding the last list item)? I have attempted using ng-disabled directly on the list item attribute ...

Creating seamless shading effects using three.js with Blender integration

When I import a Blender scene into a three.js environment, the curved faces appear flat. Is there a method to ensure that these surfaces remain smooth as intended? Despite calculating vertex normals and activating the smoothShaded option, the issue persis ...

Special character decoding in JSON format

My string is test éàå. When I use json_encode, the special character changes to test u00e9u00e0u00e5. After using json_decode, I am unable to retrieve the original characters and it remains as test u00e9u00e0u00e5 Does anyone know how to recover th ...