问题
I need to import JSON data and pull out specific things from it and am having trouble doing it.
This is the sample data:
{
"0bEiO5zcBCHv3Wd2lxHjjRepB":{
"name":"math",
"credits":4,
"professors":[
"Samatha"
],
"description":"come and learn some math",
"prereqs":"",
"comment":"",
"maxEnrollment":100,
"times":[
{
"day":2,
"start":900,
"end":1100
},
{
"day":4,
"start":900,
"end":1100
}
],
"departments":[
"mathematics"
],
"submitted":true
},
"BsSbrbjTH5FyV7gWdPjeDPqpw":{
"name":"biology",
"credits":4,
"professors":[
"Reuven"
],
"description":"learn about biology and stuff",
"prereqs":"",
"comment":"",
"maxEnrollment":20,
"times":[
{
"day":3,
"start":900,
"end":1100
},
{
"day":4,
"start":900,
"end":1100
}
],
"departments":[
"biology"
],
"submitted":true
}
}
I want to try and pull out the name, description, and professor for each one.
I import the data like so:
$.get( "/api/v1/demoschool_jacob/proposedCourses", function( data ) {
app.proposedCourses = data;
})
回答1:
Create a
computed
propertyUse Object.values to return an array of the
proposedCourses
object properties valuesUse Array.prototype.map to get the
name
,description
andprofessors
properties of each object.
The computed property will return:
Object.values(this.proposedCourses).map(({ name, description, professors }) => ({ name, description, professors }))
After that, use v-for
to iterate over the computed
property.
Vue.config.productionTip = false
Vue.config.devtools = false
new Vue({
el: '#app',
data() {
return {
proposedCourses: {
"0bEiO5zcBCHv3Wd2lxHjjRepB": {
"name": "math",
"credits": 4,
"professors": [
"Samatha"
],
"description": "come and learn some math",
"prereqs": "",
"comment": "",
"maxEnrollment": 100,
"times": [{
"day": 2,
"start": 900,
"end": 1100
},
{
"day": 4,
"start": 900,
"end": 1100
}
],
"departments": [
"mathematics"
],
"submitted": true
},
"BsSbrbjTH5FyV7gWdPjeDPqpw": {
"name": "biology",
"credits": 4,
"professors": [
"Reuven"
],
"description": "learn about biology and stuff",
"prereqs": "",
"comment": "",
"maxEnrollment": 20,
"times": [{
"day": 3,
"start": 900,
"end": 1100
},
{
"day": 4,
"start": 900,
"end": 1100
}
],
"departments": [
"biology"
],
"submitted": true
}
}
}
},
computed: {
courses() {
return Object.values(this.proposedCourses).map(({
name,
description,
professors
}) => ({
name,
description,
professors
}))
}
}
})
<script src="https://vuejs.org/js/vue.js"></script>
<div id="app">
<ul>
<li v-for="{ name, description, professors } in courses" :key="name">
<p>{{ name }}</p>
<p>{{ description }}</p>
<p>{{ professors }}</p>
</li>
</ul>
</div>
回答2:
you could use like
for(var prop in data) {
var obj = {
name: prop.name,
description: prop.description,
professor: prop.professor
};
console.log(obj); // U can use this obj object to applu your further logic
}
来源:https://stackoverflow.com/questions/51711907/need-help-parsing-imported-json-data-with-vue-js-javascript