Vue JS2按ID查找数组值

时间:2018-12-24 03:35:11

标签: vue.js

如何从Vue JS中的数组中按ID获取值?非常感谢解决方案

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

1 个答案:

答案 0 :(得分:0)

使用Array.find方法,该方法返回满足提供的测试功能的数组中第一个元素的值

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
)