Loop through each object within an array and verify if a specific property containing an array matches a given value in JavaScript

I am looking for a way to iterate over objects within an array that contains another array called userHandle. I need to loop through the userHandle array and check if any of the values match a string I define as uid. Can anyone provide me with Javascript code to accomplish this?

Array [
      Object {
        "avatar": null,
        "hugCount": 2,
        "id": 35,
        "liked": false,
        "name": "fhfdhdhf",
        "text": "Yoho",
        "timestamp": 1610471860157,
        "uid": "FOgepuJqxXfkHxI8OAV2KMWodXo1",
      },
      Object {
        "avatar": null,
        "hugCount": 1,
        "id": 34,
        "liked": true,
        "mood": 2,
        "name": "fhfdhdhf",
        "text": "I'm fine today.",
        "timestamp": 1607943705709,
        "uid": "FOgepuJqxXfkHxI8OAV2KMWodXo1",
        "userHandle": Array [
          "Aw8AUj1mPkON1Fd1s6LhkNETHfb2",
          "LrIwIx9I1xQBJ7aeCSrinpEaDP53",
        ],
      }]
    

Answer №1

Give this code a try:

var user_id = "LrIwIx9I1xQBJ7aeCSrinpEaDP53";

someArray.forEach(function(element, index){
  return element['handle']?.includes(user_id);
});

The '?' is added to ensure that the 'handle' property exists in your object

Answer №2

This specific function is the solution you've been searching for... and right below, you'll find a demonstration of how to apply it.

All you need to do is provide the value you're seeking and the array containing the data.


function locateInUserHandle(valueToFind, dataArray)
{
  return dataArray.reduce
  (
    (accumulated, currentElement) => 
      currentElement.userHandle && currentElement.userHandle.indexOf(valueToFind) !== -1 || accumulated,
      false
  )
}

let dataArray = [
  {
     "avatar": null,
     "hugCount": 2,
     "id": 35,
     "liked": false,
     "name": "fhfdhdhf",
     "text": "Yoho",
     "timestamp": 1610471860157,
     "uid": "FOgepuJqxXfkHxI8OAV2KMWodXo1",
   },
  {
     "avatar": null,
     "hugCount": 1,
     "id": 34,
     "liked": true,
     "mood": 2,
     "name": "fhfdhdhf",
     "text": "I'm fine today.",
     "timestamp": 1607943705709,
     "uid": "FOgepuJqxXfkHxI8OAV2KMWodXo1",
     "userHandle":[
       "Aw8AUj1mPkON1Fd1s6LhkNETHfb2",
       "LrIwIx9I1xQBJ7aeCSrinpEaDP53",
     ],
   }
 ]
 
locateInUserHandle('specificValue', dataArray) //?  false
locateInUserHandle('Aw8AUj1mPkON1Fd1s6LhkNETHfb2', dataArray) //? true
locateInUserHandle('mood', dataArray) //?  false

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

How can I construct a tree structure in JavaScript using JSON data when calling a function?

http://jsfiddle.net/2kwkh2uL/5498/ Here's a code snippet I've been experimenting with, attempting to create a jsTree through a JavaScript function call. However, it seems like the tree is not being built as expected. When I load the code normal ...

Send the chosen item from the <b-form-select> element to the parent component through props

Using Vue.js, I have successfully created a form where all input fields pass their values except for the <b-form-select> element. How can I pass the value of the selected option in <b-form-select> to the parent component? Child Component: < ...

Select the text inside the current cell of a jqGrid table

The issue at hand is that when using jqGrid with cellEdit:true, users are unable to select text in a cell. Once the mouse button is released, the selection resets. This limitation prevents users from copying the selected text within cells. Has anyone enco ...

` `$(document.documentElement) selecting a particular element` `

Here is a function that I am working with: jQuery(document.documentElement).on('click touch', function(e) { // check if $(e.target) matches with $('ul#menu-navigation > li.menu-item') // or any child elements within this spe ...

Gulp JS task is generating a NodeError due to the callback being triggered more than once

Error Encountered in Gulp JS Task - NodeError: Callback called multiple times Among the five Gulp JS tasks that I have, one specific task named js_bundle is causing a NodeError. The exact error message is: NodeError: Callback function called multiple ti ...

Exploring the implementation of constructors and classes in JavaScript

I have a task to create a class named ShoppingCart with specific instructions: The class should have a constructor that initializes the total attribute to zero and creates an empty dictionary attribute called items. There should be a method named add_ite ...

Tips for inserting an item into the parent window: Chrome-specific (compatible with all other browsers)

In my HTML file, I have an iFrame element like this: <iframe src="frame.html" width="2000" height="1000"></iframe> When trying to use jQuery's append function from within the iFrame to add a DIV to the parent window, it works fine in Fir ...

Can you provide instructions on converting .stl files to .png format using Python, as well as how to extract their dimensions?

Is there a way I can convert .stl files to .png format for preview purposes using Python? Additionally, how can I extract the dimensions of .stl files such as volume, height, and width? I currently view my .stl files with Three.js, but I am struggling to ...

Could you please direct me to the section in the ECMAScript documentation that specifies the behavior of a resolved promise with its [[Promise

My objective is to compare the behavior of a promise's resolve function with the corresponding process outlined in the ECMAScript specification. Specifically, I am interested in understanding how the resolve function behaves when called with an object ...

using eloquent in vuejs to fetch database columns

I am currently attempting to retrieve data from a database using an AXIOS get request. I have two models, Content and Word, which have many-to-many relationships. In my controller, I am trying the following: public function fetchCourses(){ $dayOne = C ...

Creating dynamic dropdowns with Ajax and HTML on the code side

I have developed a script that generates a drop-down menu and updates the .box div with a new color and image. Below is the HTML & Java code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <div> ...

Utilizing the onscroll feature to trigger a function within a ScrollView

I am facing an issue with an animated view where I need to execute multiple events within the onScroll property. The current onScroll implementation is as follows: onScroll={ Animated.event( [{ nativeEvent: { conten ...

Issue with retrieving JSON data through HTTP Get request on Internet Explorer, while it works fine on

Trying to upgrade a basic weather plugin by integrating geolocation services that identify a user's location based on their IP address. Smooth sailing on Chrome and Firefox, but IE seems to be causing some trouble. Any idea what might be the issue wit ...

Combining arrays encoded in JSON format

Consider the following array examples: $array1 = [ 'test' => json_encode([ 'key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3' ]) ] Now, let's ...

Mongoose - run a function on a designated date within the document

Currently, I am developing a cryptocurrency-based betting game project. My database of choice is mongodb and I utilize mongoose for interaction with it. Within this database, I have a collection that houses documents detailing various betting games. Each d ...

Dispatching identification to controller after submission

I am encountering an issue with a page that contains the following code: <div class="col-sm-2 displaybutton"> <div data-point-to="displaysHeader"> @using (Html.BeginForm("Administration", "Home", FormMethod.Post)) ...

Creating an Angular loading component using the route parameter

When a user clicks on a link in the home component, I want to load a different component based on the URL parameter. For example, if the user is at "/home" and sees a list of links: Link 1 Link 2 Clicking on Link 1 should load the details component with ...

Instructions for saving a binary file on the client using jQuery's .post function

I am working with a handler that has the following code: HttpRequest request = context.Request; HttpResponse response = context.Response; if (request["Type"] != null) { try { string resultFile = null; ...

What is the best approach for incorporating multiple conditions in a React component?

I currently have a button labeled Description. When this button is clicked, the description is displayed. Now, I am looking to include a Read more/less option for the description. Unfortunately, using the below code, I am unable to see the button labeled ...

Can React Native support styling using server-side data?

One of my React Native (RN) components is rendering data from an external server. The data is enclosed within RN components. For example: ... <View> <Text>{this.props.db.greeting}</Text> </View> The 'DB' object is si ...