我是编程新手,我将成为前端开发人员。作为练习的一部分,我试着做一个简单的网络应用程序。
但切中要害。
我在尝试过滤/切片JSON对象时卡住了--只有从控制台得到的是:“slice/filter不是一个函数”。我知道这些函数是针对数组的,但我不知道如何将JSON对象转换为JSON数组。我在网上找了很多工作人员,试图实施,但没有成功。
代码是这样的:
<template>
<div class="class">
<section v-if="errored">
<p>We're sorry, we're not able to retrieve this information at the moment, please try back later</p>
</section>
<section v-else>
<div v-if="loading">Loading...</div>
<div class="row" v-else>
<div>
<div v-for="vehicle in filteredVehicles">
<img v-for="car in vehicle.cars" v-bind:src="car.url" v-bind:alt="car.name">
</div>
</div>
</div>
</section>
</div>
null
<script>
import axios from 'axios';
export default {
data() {
return {
vehicles: [],
loading: true,
errored: false
}
},
mounted() {
axios
.get('https://urlurlurl/vehicles.json')
.then(response => (this.vehicles= response.data))
.catch(error => {
console.log(error)
this.errored = true
})
.finally(() => this.loading = false)
},
computed: {
filteredVehicles: function () {
return this.vehicles.filter(function (v) {
return v.name === ('aaa' || 'bbb')
})
}
}
}
</script>
数据结构示例:
{
"1": {
"firstname": "",
"lastname": "",
"age": {
"1": {
"name": "",
"url": ""
},
"3": {
"name": "",
"url": ""
}
}
},
"2": {
"firstname": "",
"lastname": "",
"age": {
"6": {
"name": "",
"url": ""
},
"7": {
"name": "",
"url": ""
}
}
}
// etc.
}
提前感谢你的帮助。
看起来您的数据是键/值对的对象。不幸的是,大多数浏览器都不支持object.values
,后者只提供对象值的数组:
return Object.values(this.vehicles) // Array of vehicle objects
.filter(function (v) {
return v.name === ('aaa' || 'bbb')
})
。。。但是有一个object.keys
方法得到了很大程度上的支持,因此您可以通过两步过程获得值:
return Object.keys(this.vehicles) // Array of keys in the JSON obj
.map(key => this.vehicles[key]) // Array of vehicle objects
.filter(function (v) {
return v.name === ('aaa' || 'bbb')
})
或者如果您想要使用类似lodash
的东西,这将为您提供一些更方便的函数来处理操作对象。
将其放入app.js文件中
Vue.filter('snippet',function (val) {
return val.slice(0,100);
})
当您想要使用它时,只需将snippest放入您的html中,如下所示。
<p class="card-text mb-auto">{{product.description | snippet}}</p>