如何检查具有某些数据的对象是否在 javascript 中的数组中?

How to check if object with some data is in array in javascript?

我目前使用的编程语言是Vue。 我这里有一些演示代码:

<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>

那么我如何检查 list 是否包含名称为 lava 的对象,然后 return 该对象的种类,即 liquid

您可以使用您想要的 find 和 return 字段:

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')
So how can I check if list contains the object with name lava and then return the kind of that object, which will 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>