chilledMonkeyBrain
chilledMonkeyBrain

Reputation: 141

Search for key in JSON, Parse in Vue

In my Vue.js project. The user can input any text. I need to search for this input as a key in local JSON file, return the attribute and parse into a string.

<template>
  <div>
    <input v-model="userInput" placeholder="search fruit">
    <p>The color of {{ userQuery }}s is {{ returnedColorResult }}</p>
  </div>
</template>

<script>
  export default {
  input: 'Userinput',
  data () {
    return {
    userQuery: ''
  }
 }
}

Now I have their input stored here {{ userQuery }}.

The JSON is

{
"banana" : "yellow",
"orange" : "orange",
"pear" : "green",
"apple" : "red"
}

My incomplete search script is

<script>
 import json from "../data/fruitColors.json"
 export default {
     data() {
         return {
             myJson?: json?
         }
     }
 }
</script>

How do I take what I have in {{ userQuery }} search for it in the JSON, return the paired attribute and make it available for the {{ returnedColorResult }} ?

Any help greatly appreciated.

Upvotes: 0

Views: 1146

Answers (1)

Bert
Bert

Reputation: 82439

A very basic Vue example of how you might do this.

console.clear()

const json = {
"banana" : "yellow",
"orange" : "orange",
"pear" : "green",
"apple" : "red"
}

new Vue({
  el: "#app",
  data () {
    return {
      userQuery: '',
      json
  }
 }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
  <div id="app">
    <input v-model="userQuery" placeholder="search fruit">
    <p>The color of {{ userQuery }}s is {{ json[userQuery] }}</p>
  </div>

Upvotes: 2

Related Questions