获取与特定值匹配的JSON对象

时间:2019-05-18 14:52:19

标签: javascript json vue.js filter

我正在构建一个小的Web应用程序来练习和学习Vue.js并使用API​​。

对于我要解决的特定问题,我想返回具有我请求的匹配uuid的对象。

根据我目前的知识,我知道我可以通过实现某种排序和循环逻辑来做到这一点。

但是我仍然对JS Vue.js还是陌生的,所以我不确定是否有更好的方法来解决这个问题。

是否有内置函数或某种形式的“最佳实践”来解决这个问题?

methods: {
    fetchItem(row) {
        // row.target_uuid  -- this is the UUID I want
        // this.$props.todoItems;   -- this contains the json objects
        // return this.$props.todoItems[i] where this.$props.todoItems[i]['uuid'] == row.target_uuid
},

这是我的上下文$ props.todoItems的代码段

[
  {
    "title": "Install Maris",
    "uuid": "9ec9ea6b-0efc-4f6a-be2e-143be5748d3a",
    "field_completed": "False"
  },
  {
    "title": "Figure out why VS Code sucks",
    "uuid": "85120da5-ee59-4947-a40f-648699365c73",
    "field_completed": "False"
  },
  {
    "title": "Start designing portfolio",
    "uuid": "243c1960-7ade-4a68-9a74-0ccc4afa3e36",
    "field_completed": "False"
  },
  {
    "title": "Meal Prep",
    "uuid": "85b64b18-9110-44d8-bd2d-8f818b0a810f",
    "field_completed": "False"
  },
  {
    "title": "Sharpen knives",
    "uuid": "8a7ac5f6-8180-4f20-b886-628fd3bcfc85",
    "field_completed": "False"
  },
  {
    "title": "Set up SSH keys",
    "uuid": "f879c441-8c05-4f24-9226-125c62576297",
    "field_completed": "False"
  }
]

1 个答案:

答案 0 :(得分:1)

如果您知道要查找的只是一个项目(或匹配的第一个项目),则应仔细查看JS提供的Array.find()方法。 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
还请看一下Array原型提供的所有其他方法,其中大多数方法都是描述性的,可以解决您将遇到的大多数基本问题。

要在Vue应用程序中使用此功能,您可以使用一种方法,根据提供的uid来返回待办事项,例如这样

todoByUid(uidToFind) {
  return this.todos.find(todo => todo.uid == uidToFind)
}

如果您只关心当前选定的项目,那么可以按照Jacob提到的那样计算值:

computed() {
  selectedTodo() {
    return this.todos.find(todo => todo.uid == this.selectedUid)
  }
}
相关问题