Ways to verify the presence of a key within an array of objects

I'm on a mission to determine whether a specified key exists in an array of objects. If the key value is present, I need to return true; otherwise, false.

I enter the key into a text box as input and then attempt to check if it exists in the array of objects, but so far, no luck.

Here's what I've attempted:

code:

var obj = [{
    "7364234":"hsjd",
    "tom and jerry":"dsjdas",
    "mickey mouse":"kfjskdsad",
    "popeye the sailor man":"alkdsajd",
    "the carribean":"kasjdsjad"
}]

var val = $("input[name='type_ahead_input']").val();

if (obj[val]) {
    console.log('exists');
} else {
    console.log('does not exist');
}

If I input 'the carribean', which does exist in the object array, it still displays 'does not exist' in the console output.

How can I troubleshoot and fix this issue?

Answer №1

To determine if there are objects in the array that contain a specific key, you can filter the array and only return the objects that have the desired key. If the resulting array has a length greater than zero, it indicates that there are elements with that key present.

var obj = [{
    "7364234":"hsjd",
    "tom and jerry":"dsjdas",
    "mickey mouse":"kfjskdsad",
    "popeye the sailor man":"alkdsajd",
    "the carribean":"kasjdsjad"
}];

var val = "the carribean";

var exists = obj.filter(function (o) {
  return o.hasOwnProperty(val);
}).length > 0;

if (exists) {
    console.log('exists');
} else {
    console.log('does not exist');
}

If the array contains objects with the desired key, regardless of whether the value is undefined or null, this code will output true.

Answer №2

Checking for the existence of a key in an object can be done using typeof.

if (typeof obj[0][val] !== "undefined" ) {
    console.log('exists');
} else {
    console.log('does not exist');
}

It's important to note that the index 0 is used because the object being checked is element 0 of the array obj.


Here is a fiddle:

var obj = [{
"7364234":"hsjd",
"tom and jerry":"dsjdas",
"mickey mouse":"kfjskdsad",
"popeye the sailor man":"alkdsajd",
"the carribean":"kasjdsjad"
}];

if ( typeof obj[0]["the carribean"] !== 'undefined' ) {
console.log('exists');
} else {
console.log('does not exist');
}


As suggested by Cristy below, another way to check for key existence is using obj[0][val] === undefined

You can also try this:

var obj = [{
    "7364234":"hsjd",
    "tom and jerry":"dsjdas",
    "mickey mouse":"kfjskdsad",
    "popeye the sailor man":"alkdsajd",
    "the carribean":"kasjdsjad"
}];

var val = "7364234";

if ( val in obj[0] ) {
    console.log('exists');
} else {
    console.log('does not exist');
}

Answer №3

If you're looking to determine the existence of a key and retrieve its value from an array, I recommend using Array.some() along with Array.find(). Here's some code showcasing this approach:

let arr = [{"foo": 1}, {"bar":2}];

function isKeyInArray(array, key) { 
  return array.some(obj => obj.hasOwnProperty(key)); 
}

function getValueFromKeyInArray(array, key) { 
  return array.find(obj => obj[key])?.[key]; 
}

console.log(isKeyInArray(arr, "foo"), isKeyInArray(arr, "bar"), isKeyInArray(arr, "baz"));
console.log(getValueFromKeyInArray(arr, "foo"), getValueFromKeyInArray(arr, "bar"), getValueFromKeyInArray(arr, "baz"));

Answer №4

To determine if a specific key exists in any of the objects within an array, you must iterate through each object's keys.

var objArr = [{
  "7364234": "hsjd",
  "tom and jerry": "dsjdas",
  "mickey mouse": "kfjskdsad",
  "popeye the sailor man": "alkdsajd",
  "the carribean": "kasjdsjad"
}]

const contains = (string) =>
  objArr.findIndex(
    // Is the string part of the object keys?
    obj => Object.keys(obj).includes(string)
  ) !== -1

console.log(contains('the carribean'))
console.log(contains('spaghetti'))

Answer №5

The reason for the issue is due to having an array of objects [{...},{...}] instead of just a single object {...}. To resolve this, you can either switch to using a single object with your test or utilize the Array.find method to check if an object with the property val exists in your array. Here's an example:

var objArr = [{
    "7364234":"hsjd",
    "tom and jerry":"dsjdas",
    "mickey mouse":"kfjskdsad",
    "popeye the sailor man":"alkdsajd",
    "the carribean":"kasjdsjad"
}]

let val = $("input[name='type_ahead_input']").val();

var existingObj = objArr.find(function(element) {
  return typeof element[val] !== 'undefined';
});

if (existingObj[val]) {
console.log('was found');
} else {
console.log('not-found');

For more information, refer to: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/find

Answer №6

To retrieve the specific object from the array, you will need to access it using the syntax obj[0][val]

var processData = function() {
  var obj = [{
    "7364234": "hsjd",
    "tom and jerry": "dsjdas",
    "mickey mouse": "kfjskdsad",
    "popeye the sailor man": "alkdsajd",
    "the carribean": "kasjdsjad"
  }];

  var val = $("input[name='type_ahead_input']").val();
  console.log(val);
  if (obj[0][val]) {
    console.log('Object exists');
  } else {
    console.log('Object does not exist');
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input name="type_ahead_input" value="" onkeyup="processData()">

Answer №7

One of the simplest solutions, in my opinion, is provided by @E. Sundin. In my own scenario, I achieved the desired outcome using the following approach...

let person = { 
    id: 2, 
    name: "jack", 
    age: 54, temp: 2323
}

if(!Object.keys(person).includes('id')) throw new BadRequest("Id was missing!");

If you're dealing with an array of objects created through a loop...

if(!person.every(elm => Object.keys(person).includes('id')) throw new BadRequest("Id was missing!");

This should hopefully get the job done.

Answer №8

Check out this code snippet:

let students = [{ firstName:'John' }, { email:'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="364d4e5b48515a7d77717c7b39747775">[email protected]</a>' }, { grade: 'A' }]

const hasEmail = students.some(item => item.hasOwnProperty('email'))

console.log('Email found in array: ', hasEmail);

Answer №9

    Using the Array.find() method helps find a specific key within an array of objects and returns true or false.

This is a straightforward way to verify the existence of a key in an array of objects.

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

Employing an item as a function

My query pertains to utilizing an express application object (app object) as a callback function. The express application is known for its methods and properties that aid in handling HTTP requests. When integrating the app object with an HTTP server, it se ...

The clearfix feature is ineffective when using AngularJS

<ul class="dropdown-menu wm_search_div" ng-show="searchDivShow"> <li ng-repeat="user in searchUserList"> <a href="javascript:void(0);" class="wm_clearfix3"> <img ng-src="{{user.faceIcon}}" class="pull-left wm_se ...

Exploring the dimensions of a Numpy array

Is there a way to determine the dimensions of an array like this one, which is 2x2: matrix = np.array([[1, 2], [3, 4]]) ...

Combining numerous base64 decoded PDF files into a single PDF document with the help of ReactJS

I have a scenario where I receive multiple responses in the form of base64 encoded PDFs, which I need to decode and merge into one PDF file. Below is the code snippet for reference: var pdf_base1 = "data:application/pdf;base64,JVBERi0xLjQKJfbk/N8KMSAwIG9 ...

Is Implementing a Promise for Preprocessing in NodeJS Worth It?

Looking to achieve the following using NodeJS + Express: Client sends a post request with JSON document data={text: "I love Stackoverflow", shouldPreprocess: <true or false>}; Need to call an external WebSocket service for sentiment analysis on the ...

What is the best way to ensure that consecutive if blocks are executed in sequence?

I need to run two if blocks consecutively in TypeScript, with the second block depending on a flag set by the first block. The code below illustrates my scenario: export class Component { condition1: boolean; constructor(private confirmationServic ...

Click event inside a repeat loop

Working with AngularJS, I have a collection of colors that each have a specific title and type. These colors are displayed in a list format on the webpage. Now, I am looking to enhance this by incorporating a menu option that allows users to filter and vi ...

Header formatting issue when attempting to implement tablesorter plugin

I implemented the widget-scroller and widget column Selector in my table using the table sorter plugin in jQuery. Has anyone encountered a problem like the one shown in this picture? It seems that my table headers do not align with the columns properly an ...

What is the best way to incorporate a variable in the find() method to search for similar matches?

I've been working on a dictionary web application and now I'm in the process of developing a search engine. My goal is to allow users to enter part of a word and receive all similar matches. For instance, if they type "ava", they should get back ...

"Utilize Meteor to transmit emails to internal email addresses within the intran

I have successfully developed a Meteor App to manage requests. However, I am facing an issue where I need emails with default text to be sent whenever a request is created or updated. The challenge lies in the fact that I am operating within an intranet e ...

Struggling with integrating Bootstrap 4 Modals in Angular 2 environment

I attempted to incorporate a modal from into my navbar, but nothing happens when I click on it. <div class="pos-f-t fixed-top header"> <nav class="navbar navbar-inverse bg-inverse navbar-toggleable-md"> <button class="navbar- ...

An incorrect object was removed from the array

Having an issue where the wrong item is getting deleted from an array in my component's state. Here is a simplified version of my parent Component: export default class BankList extends Component { state = { banks: [new Bank("Name1"), new ...

What could be causing the JSF ajax status success to fail in Chrome?

Whenever I trigger an action in my ManagedBean, I also initiate a JavaScript function via JSF ajax to display a loading popup while the action is being processed. This functionality works flawlessly in Firefox, however, it seems to encounter issues in Chro ...

Creating a unique filter that combines and filters data from two separate API calls for

In my current scenario, I am making two different API calls using Axios in my application. The first call fetches a complete JSON file that populates a table, while the second call retrieves only categories. This setup is due to the complexity of the app, ...

Increasing the contents of a JavaScript array within a conditional statement

I find myself in a predicament where I need to dynamically add elements to a multidimensional array depending on a specific condition. This means that the type of element to be added will vary based on the condition. if(type == 'text-box'){ ...

Retrieving Data from a Nested JSON Array

How do I modify my JavaScript code to extract the last 3 values from the JSON list provided below? The current code is unable to read these values with different formatting. Example section of the JSON list: {...... 'Design_Lump_Sum': {0: {&a ...

In what way can I incorporate additional functions or multiple functions within an Express route to modify database information?

Currently, I am working on a project that involves Express and MySQL. One of the challenges I am facing is retrieving data from a connection.query and then utilizing that data in other functions within the same route. My goal is to use the array created in ...

Display various images based on different device orientations in UIWebView

Is there a way to display varying images in my HTML on a UIWebView, depending on the orientation of an iPhone? (I apologize if this question seems basic...) ...

Releasing memory allocated for struct.name (warning: HEAP CORRUPTION IDENTIFIED)

Having an issue while attempting to free memory allocated with malloc in dynamic arrays created based on the length of a user-inputted name. The "Debug error" occurs when I try to use the free() function. typedef struct { char *nombre; float nota; ...

Exploring CakePHP 3's capabilities with JSON response: Enhancing response data format by connecting with related tables

I am working with two tables, each with their own set of attributes: Sessions id staff_id Staff id firstname lastname When a link is clicked, it triggers a JavaScript function to open a modal. An AJAX call is then made to retrieve data in JSO ...