How to split up a JSON file for use in Drop Down box
-
23-12-2019 - |
题
I'm using Marionette/Backbone and i have a JSON file with multiple objects, i need to populate a select box with items from this JSON file. So a drop down box for accountType, States and dates.
At the moment i only care about the accountType, but i can't find a way of splitting the JSON file up so that the drop down shows only "Full" or "Trial".
I have a JSON file which looks similar to this:
{
"accountType":["Full","Trial"],
"states": [{"state":"AL","stateDescription":"Alabama","featured":"A1"},
{"state":"AK","stateDescription":"Alaska","featured":"B1"}],
"dates":[{"dateDescription":"Jan","month":1,"year":2008},
{"dateDescription":"Feb","month":2,"year":2008}]
}
I didn't write the JSON file it's what i have to use - i access it in my .js file like so:
initialize: function () {
this.on('change', this.change);
var that = this;
$.getJSON("webapp/jsondata", function (data) {
that.set('accountType', data);});
}
But in my drop down box i basically get:
Full, Trial
[object Object], [object Object]
In that sort of format.
I think i understand why and it's because im not splitting up the JSON file but just can't work out how to do it. Read pages and pages online but nothing seems appropriate.
Any advice appreciated, please be gentle.
EDIT:---
Here's the whole code in the backbone data. This now works to populate the accountType box but when i replicate it with the other drop downs all of them turn blank.
define([ 'backbone', 'underscore', 'vent', ], function (Backbone, _, vent) {
'use strict';
return Backbone.Model.extend({
url: {},
loaded: false,
defaults: {
accountType: [],
states: [],
dates: [],
},
initialize: function () {
this.on('change', this.change);
var that = this;
$.getJSON("webapp/jsondata", function (data) {
that.set({
states: data.states,
});
});
$.getJSON("webapp/jsondata", function (data) {
that.set({
dates: data.dates,
});
});
$.getJSON("webapp/jsondata", function (data) {
that.set({
accountType: data.accountType,
});
});
},
});
});
I'm guessing it's because AccountType has only 1 attribute while "states" have State, description and featured. I want to only pick out for example "AL" and "AK". So i need a way of slicing my data (i think) and allocating it to the drop downs.
Edit--
Here's the view code:
define([ 'marionette', 'templates', 'vent', 'select'],
function (Marionette, templates, vent, select) {
"use strict";
return Marionette.ItemView.extend({
template: templates.inputView,
serializeData: function () {
return {
states: this.options.meta.get('states'),
dates: this.options.meta.get('dates'),
accountType: this.options.meta.get('accountType'),
};
},
});
});
解决方案 2
A more specific question was asked here which sorted me out:
其他提示
You can use the parse
method of model/collection.
Take a look at the documentation
Try this :
initialize: function () {
//this.on('change', this.change);
this.fetch();
}