Converting an ajax JSON object into an array


#1

I’m relatively new to Ember, and I’m trying to get my head around the correct Ember way of manipulating data pulled in via an AJAX call before setting it as the model (so it can be used in the template).

The short version is the JSON is an object full of objects. I (think I) need it to be an array of objects so I can loop through the array in the template and build a <select> list.

Initially my thinking was to do something like this in the route:

import Ember from 'ember';

export default Ember.Route.extend({
	model() {
		return Ember.$.getJSON('/json/data.json', function(data) {
			let arr = [];
			Ember.$.each(data, function(index, value) {
				arr.push(value);
			})
			return arr;
		});
	}
});

But when I {{log model}} in the template, I still have the original object. Which in hindsight, I think makes sense.

Any suggestions on how I can achieve what I’m after?


#2

Maybe it depends on your json, but I don’t think you have to manually insert it into an array to access it via a view.

Example, in my router.js:

model () { var members = Ember.$.getJSON("/data/members.json"); return members; }

Within my view I can loop through each json object by passing the data to a component:

`{{team-profile members=model}}`

and my components view looks like this:

{{#if members}}
    {{#each members as |member|}}
    <div class="area team">
        <div class="container">
            <div class="row">
                <div class="col-xs-12 col-lg-3">
                    <img alt="" src="{{member.image}}"/>
                </div>
                <div class="col-xs-12 col-lg-7">
                    <h1>
                        {{member.name}}
                    </h1>
                    <h4>
                        {{member.position}}
                    </h4>
                    <p>
                        <a href="{{member.email}}">{{member.email}}</a>
                    </p>
                    {{{member.content}}}
                </div>
            </div>
        </div>
    </div>
    {{/each}}
{{else}}
    <div class="container">
        No members to display.
    </div>
{{/if}}
{{yield}}

My json file is composed a couple members stored like so:

{
        "name": "Member Name",
        "position": "Member Position",
        "email": "member@site.com",
        "image": "/img/member.jpg",
        "content": "<p> Member content</p>"
    },