4

How can i get the value by id from a array in vue js? Many thanks with solution

list = [
    {
        "name": "Apple",
        "id": 1,
    },
    {
        "name": "Orange",
        "id": 2,
    }
]
watch: {
    food: function (val) {
        //Get food name by val(id)
    }
}

1 Answer 1

7

Use Array.find method, which returns the value of the first element in the array that satisfies the provided testing function:

var food = list.find(food => food.id === val)
var name = food ? null : food.name

let list = [
    {
        "name": "Apple",
        "id": 1,
    },
    {
        "name": "Orange",
        "id": 2,
    }
]

console.log(
  list.find(food => food.id === 1).name
)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.