How can you verify the presence of an object containing specific data within an array using JavaScript?

Currently, I am working with the Vue programming language and have some demo code to showcase:

<template>
  <button @click="checkInList">Check</button>
</template>

<script>
import { ref } from "@vue/reactivity";

export default {
  name: "App",
  setup() {
    const firstInput = ref("");
    const secondInput = ref("");
    const list = ref([
      { name: "lava", kind: "liquid" },
      { name: "air", kind: "gas" },
      { name: "water", kind: "liquid" },
      { name: "earth", kind: "object" },
    ]);
    const checkInList = () => {
      if (list.value.includes({ name: "lava", kind: "liquid" })) {
        console.log("array includes lava");
        // here I want to return the kind of that element, which will be liquid
      }
    };

    return {
      firstInput,
      secondInput,
      checkInList,
    };
  },
};
</script>

To determine whether list has an entry with the name lava and then retrieve the type of that entry, which is likely to be liquid, how can this be done?

Answer №1

To retrieve the desired field, you can utilize the find method:

const { ref } = Vue
const app = Vue.createApp({
  setup() {
    const firstInput = ref("");
    const secondInput = ref("");
    const list = ref([
      { name: "lava", kind: "liquid" },
      { name: "air", kind: "gas" },
      { name: "water", kind: "liquid" },
      { name: "earth", kind: "object" },
    ]);
    const checkInList = () => {
      return list.value.find(l => l.name.includes(firstInput.value)).kind
    };

    return {
      firstInput,
      secondInput,
      checkInList,
    };
  },
})
app.mount('#demo')
I want to determine if the list includes the object with the name lava and then provide the kind of that object, which would be liquid.
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <button @click="checkInList">Check</button>
  <input v-model="firstInput" />
  <p>{{ checkInList() }}</p>
</div>

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

Fix image that won't load in Firefox

My website features an <img /> element that initially lacks a src attribute. The src is added dynamically using JavaScript at a later point. While Chrome hides it, Firefox displays an empty space: https://i.sstatic.net/3eZJ4.png Is there a way to p ...

Can you explain the variance between calling mongoose.Schema() and creating a new instance with new mongoose.Schema()?

Can you explain the distinction between mongoose.Schema() and new mongoose.Schema() methods? I have tried both approaches, and it seems like they yield similar results. Are there any notable differences or implications to consider? ...

Want to learn how to create a draggable uploaded image on a canvas, similar to the functionality of Google

I have a question regarding the draggable feature in Canvas elements. I uploaded an image into the canvas and would like it to be draggable, similar to Google Maps. My ultimate goal is to enable zoom in and out functionalities as well. Is this achievable ...

Material User Interface, MUI, Modal, Back to Top Scroll按钮

After spending some time experimenting with scrollTop and the Dialog component (a fullscreen fixed modal) from Material-ui, I found that I couldn't quite get scrollTop to function properly. Whenever I clicked the "go down" button, it would either retu ...

Strategies for capturing a 404 error in an Express router

Trying to capture the 404 page not found error in an express router. Using a simple example : const express = require('express'); const app = express(); const router = express.Router(); // ROUTER MID BEFORE router.use((req, res, next) => { ...

Advancement of a grunt chore within a digital platform

After constructing an app with grunt, I am now in the process of developing a web interface using node and angular to interact with this app. One feature I have implemented is a button that triggers a grunt task using childProcess in NodeJS: child_process ...

Using the setTimeout function is essential for successfully extracting values in a Jquery each loop. Without

I created a loop to adjust the padding on an image tag placed atop another image. Strangely, it was only capturing the first one or two values until I added a setTimeout function, which seemed to fix the issue. Below is the jQuery code: $(document).ready ...

Having trouble with Angular + Rails combination: Angular can't seem to locate the controller

Issue: I am encountering an error in my Angular / Rails app. When trying to access a Rails controller function from the Angular controller, I receive the following error: Uncaught TypeError: tasks.moveOrder is not a function. Strangely, all other functions ...

What is the best way to access firebase information using vue and vuefire?

I'm struggling to understand how to effectively retrieve Firebase data in a Vue application. I’m prepared to delete this question or even consider leaving my position as a programmer if I can't find a solution ;) I realize that the data is asy ...

Looping through an array

I have created an array as shown below: iArray = [true, true, false, false, false, false, false, false, true, true, true, false, true, false, false, false, false, true] Condition check: If any value in this array is false, I will display an error messag ...

Why is my JSON parse function returning an empty string?

Not sure if the issue lies with VueJS or JS itself. Within my database, I have a string (converted from a JS Object using JSON.stringify()) that appears as follows: {"type":5,"values":{"7":"/data/images/structured-content/64-7-scico.jpg","8":"<b>we ...

What is the proper way to call functions that are defined within my Vue.js plugins

Recently, I created a custom Vue.js plugin that allows access to Vue functions globally: const MyPlugin = { install (Vue, options) { Vue.myFunction = function () { console.log('Test') } } } export default { MyPlugin } To ...

What is the proper method for implementing an event listener exclusively for a left mouse click?

Is there a way to make Phaser recognize only left mouse clicks as click events, excluding right and middle clicks? Check out this Phaser example at the following link: https://phaser.io/examples/v2/basics/02-click-on-an-image. ...

Guide for implementing a one-line if statement in Javascript

I am aiming to assign a class using a single-line if statement as outlined in this source. Currently, I am utilizing Material-UI and attempting to specify a class. Therefore, I would like to implement this approach: if(condition) expression <Typogr ...

What is the safest method to insert data into a div element?

After utilizing ajax to retrieve a JSON file from the web, I successfully assigned one of the keys to a variable. Now, my question is how can I display the contents of that variable within a div tag? My initial approach was: theJsonKey = jsonObject.key; ...

Invoke data-id when the ajax call is successful

Initially, there was a smoothly working "like button" with the following appearance: <a href="javascript:void();" class="like" id="<?php echo $row['id']; ?>">Like <span><?php echo likes($row['id']); ?></span ...

Utilize JQuery to inject both standard HTML elements and safely rendered escaped HTML onto a webpage

After storing some data in firebase that can be retrieved on the client side, I use JQuery to add it to the HTML. Although the process of prepending the data to the DOM element is straightforward, there is a security concern as raw code can make the applic ...

Adjusting the size and location of the current browser window using jQuery

Is there a way to modify the height, width, and position of the browser window using jQuery's document.ready() function? ...

Having trouble with my findIndex function in Node.js while working with a mongo DB database

I am having difficulty finding the index of a specific product in a MongoDB database. const cart = await this.model.findOne({ user: { $eq: user } }); if (cart) { const itemFound = cart.products.findIndex( (item) => item._id === ...

What is the process for transferring information from a Microsoft Teams personal tab to a Microsoft Teams bot?

Is it feasible to share data such as strings or JSON objects from custom tab browsers to a Teams bot's conversation without utilizing the Graph API by leveraging any SDK functionality? ...