Determine whether any element in the array matches a property of the object

Let's start with an array:

 arr=[
      "EMPRESA",
      "CD_DIRECAO",
      "DT_INI_DIRECAO"
    ]

Next, we have an object:

primary = {
           "EMPRESA": {"type": "varchar"},
           "CD_DIRECAO": {"type": "varchar"},
           "DT_INI_DIRECAO": {"type": "date"},
           "CD_DEPT": {"type": "varchar"},
           "DT_INI_DEPT": {"type": "date"},
           "ANO": {"type": "number"},
           "MES": {"type": "number"},
           "TP_CUSTO": {"type": "varchar"},
          }

The task at hand is to determine if any of the elements in arr can be found within the primary object. Any guidance on this would be greatly appreciated.

Answer №1

To determine if a key exists, you can use the Array#some method to iterate through the array.

var arr = ["EMPRESA", "CD_DIRECAO", "DT_INI_DIRECAO"],
    primary = { EMPRESA: { type: "varchar"}, CD_DIRECAO: { type: "varchar"}, DT_INI_DIRECAO: { type: "date"}, CD_DEPT: { type : "varchar"}, DT_INI_DEPT: { type: "date"}, ANO: { type: "number"},  MES: { type: "number"}, TP_CUSTO: { type: "varchar"}},
    contain = arr.some(function (k) {
        return k in primary;
    });

console.log(contain);

Answer №2

for (let index = 0; index < array.length; index++){
    if (primary[array[index]]){
        //element found
    }
}

Answer №3

To determine if a key exists in an object, you can iterate through the keys and use the indexOf method:

for (var key in myObject) {
    if (myArray.indexOf(key) !== -1) {
        console.log("Key exists");
    }
}

Alternatively, you can use Object.keys:

Object.keys(myObject).forEach(function(key) {
    if (myArray.indexOf(key) !== -1) {
        console.log("Key exists");
    }
});

Answer №4

Here is an example utilizing Array.prototype.some:

var elements=["EMPRESA","CD_DIRECAO","DT_INI_DIRECAO"];
var primary={EMPRESA:{type:"varchar"},CD_DIRECAO:{type:"varchar"},DT_INI_DIRECAO:{type:"date"},CD_DEPT:{type:"varchar"},DT_INI_DEPT:{type:"date"},ANO:{type:"number"},MES:{type:"number"},TP_CUSTO:{type:"varchar"}};

var result = elements.some(function(item){
   return primary[item];
});

console.log(result);

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

Does D3 iterate through the entire array every time we define a new callback?

It seems that every time a callback is set, d3 loops through the entire array. Initially, I thought that functions like attr() or each() were added to a pipeline and executed all at once later on. I was trying to dynamically process my data within d3&apo ...

Need help with jQuery UI and managing changing content?

Looking for suggestions on using a dynamic, single dialog that updates based on ajax calls. Is there a graceful method to adjust the height and width according to the new content? Currently encountering issues with an empty div being populated. Any assist ...

Issues arise when submitting the form on a web page with an MVC 4 partial view, causing the page

Scenario: I am currently working on a C#/MVC 4 project where I have a view that includes a partial view. The main view consists of a form with a submit button, and the partial view is initially hidden but can be displayed by selecting a checkbox. Problem: ...

When using Typescript with Mongoose, you may encounter the error message "Property 'x' does not exist on type 'Document'"

Here is my custom Mongoose model used in conjunction with TypeScript: import mongoose, { Schema } from "mongoose"; const userSchema: Schema = new Schema( { email: { type: String, required: true, unique: true, lowerc ...

When the Model popup is activated, it is essential for elements to have an adequate color contrast

Our team is utilizing the axe dev tool for accessibility testing. We encountered an issue where elements behind a model popup (Kendo React model with position: absolute) were displaying insufficient color contrast errors. Upon changing the absolute positio ...

Can Chrome Support Bookmarklets?

While attempting to craft a bookmarklet in Chrome using the console, I encountered the following error: Refused to load the script 'https://code.jquery.com/jquery-1.6.1.min.js' because it violates the following Content Security Policy directive: ...

Selecting a date in Jade's date picker

I'm currently facing an issue with getting a datepicker to function properly using Jade in a node.js and express framework. Within index.jade, I am loading the necessary javascript files like this: link(type='text/css', href='css/ui-l ...

What is the best way to retrieve a linked filter in Vue from another?

I have created a file to store filters linked to my Vue object, and it is being imported into my App.js. One of the filters I have needs to use another filter: Vue.filter('formatDateTime', value => { if (value) return moment(String(value ...

Tips for obtaining the state of a local variable in a Vue method:

How do I access the state of a local variable within a method in Vue? I am looking to set a specific value for the dialog in order to open the popUp. After loading the data, my goal is to open the popUp by using this porting method. import { mapState, m ...

Steps for Enabling or Disabling a Bootstrap-Select Dropdown based on Radio Button Selection using JavaScript and jQuery

I am facing an issue with implementing two radio buttons and a Bootstrap-select Dropdown. I need to dynamically enable/disable the dropdown based on the selection of the radio buttons using JavaScript. Below is the HTML code snippet: Here is the code snip ...

Forwarding from a user interface element in Next.JS

I am currently working on a project utilizing Next.js 13, and I have encountered a situation where I need to invoke a client-side component from a server-side page. The specific component in question is the DeleteAddressAlertDialog which interacts with my ...

Utilizing multiple optional key values in Vue Router

When working with vue-router, I am faced with the challenge of creating a route that can handle multiple optional parameters. For example, the route needs to be able to handle scenarios like: /something/a/1/b/2/c/3 /something/a/1/b/2 /something/a/1/c/3 /s ...

Received an unexpected character '?' in NextJS

After setting up a fresh installation of Ubuntu 22.04.1 LTS and installing npm and docker, I encountered an issue while trying to start my NextJS web server with the command npm run dev. An error message appeared as follows: niklas@srv-code01:~/Desktop/Co ...

Issues with Jquery Cycle not functioning as expected

I've been delving into the world of Jquery, attempting to create a basic SlideShow, but unfortunately, the desired effect isn't happening... Here's the layout of my HTML file: <!doctype html> <html lang="en"> <head> ...

press a cURL PHP ajax button to trigger an action

Hello everyone, I could really use some help here. I've been looking at similar questions but none of the answers seem to apply to my situation. I extracted a page using curl, however, there's a button on that page that I am unable to interact w ...

Mongodb Node.js - Kerberos module could not be located

After successfully installing mongodb via npm, I encountered an issue when trying to run my app. The error message received was: Error: Cannot find module '../build/Release/kerberos' from '/Users/snorre edwin/Code/raspberry-node- se ...

What is the process for sending data to a database using a URL?

I am in need of developing a public API for my application that will be capable of receiving a single POST request. The main goal is to provide users with the ability to submit data directly to my database without having to manually interact with forms on ...

The combination of Next.JS and React Objects is not acceptable as a React child

Summary: Encountering the error Error: Objects are not valid as a React child (found: [object Promise]) while making a fetch request in a Typescript project. Interestingly, the same code snippet works without errors in a Javascript project. Recently, I ...

JavaScript code that only runs during the initial iteration of a loop

I am facing an issue while trying to develop a stopwatch for multiple users using PHP and JavaScript, with MySQL database for user data storage. The problem is that the stopwatch starts when I click on one user but does not work for others. I have attempte ...

"Include the 'unsafe' prefix at the start of the URL in AngularJS

Whenever I attempt to access app://csttree?featuretype=cst_issue&verticalid=2132321&l1=3213&l2=3242 within my app, the URL gets parsed as ==> unsafe:app://csttree?featuretype=cst_issue&verticalid=2132321&l1=3213&l2=3242 Is ...