我有一个Vue.js计算的属性,如下所示。
odds() {
let race = this.data.events.runners.filter(item => item.course === this.course && item.time === this.time)
let runner = race[0].data.filter(item => item.name === this.runner)
return runner[0].odds
}
尽管它返回期望值,但我认为它看起来很脏。任何人都可以提出编写此代码的最佳方法吗?
示例JSON如下。
{
"courses": [{
"type": "horses",
"course": "Exeter"
}],
"runners": [{
"course": "Exeter",
"time": "14:10",
"data": [{
"number": "1",
"name": "White Lilac",
"odds": "6\/1"
}, {
"number": "2",
"name": "Sauvignon",
"odds": "5\/1"
}, {
"number": "3",
"name": "Foxy Lass",
"odds": "33\/1"
}, {
"number": "4",
"name": "Hot Ryan",
"odds": "8\/1"
}, {
"number": "5",
"name": "Arqalina",
"odds": "11\/8"
}, {
"number": "6",
"name": "Presenting Lucina",
"odds": "14\/1"
}, {
"number": "7",
"name": "Persistantprincess",
"odds": "12\/1"
}, {
"number": "8",
"name": "Windy Bottom",
"odds": "20\/1"
}, {
"number": "9",
"name": "Shotgun Sally",
"odds": "33\/1"
}, {
"number": "10",
"name": "Rule The Ocean",
"odds": "9\/1"
}, {
"number": "11",
"name": "Avithos",
"odds": "12\/1"
}, {
"number": "12",
"name": "Monet Moor",
"odds": "16\/1"
}]
}]
}
我想知道是否有更好的方法可以做到这一点。提前致谢。
答案 0 :(得分:0)
您现有的代码已经足够好了。但是一种变化是您的历程和时间使其成为唯一字段,因此始终只有一个索引,因此最好尽早退出。 (您可以添加虚假检查以确保自己没有找到)。
var requiredCourse = (courseDetails)=>courseDetails.course === this.selectedCourse && courseDetails.time === this.selectedTime;
var requiredhorse = (horse)=> horse.name === this.runner;
var courseIndex = data.findIndex(requiredCourse);
var horseOdds = data[courseIndex].data.findIndex(requiredhorse);
console.log(data[courseIndex].data[horseOdds])
但是如果您有能力更改JSON结构。然后直接将课程和时间作为关键,因此您无需过滤或findIndex即可直接访问。希望这样会让您喜欢的清洁一点。