Construct models from a Collection fetch in Backbone.js - javascript

I am using Backbone to retrieve data over a REST API. My code is as follows:
var PlayerModel = Backbone.Model.extend({});
var PlayersCollection = Backbone.Collection.extend({
url: "http://api.football-data.org/v1/teams/81/players",
model: PlayerModel
});
var catalons = new PlayersCollection();
catalons.fetch();
This is the JSON output I receive if I do a GET request in POSTMAN
{
"_links": {
"self": {
"href": "http://api.football-data.org/v1/teams/81/players"
},
"team": {
"href": "http://api.football-data.org/v1/teams/81"
}
},
"count": 24,
"players": [
{
"name": "Marc-André ter Stegen",
"position": "Keeper",
"jerseyNumber": 1,
"dateOfBirth": "1992-04-30",
"nationality": "Germany",
"contractUntil": "2019-06-30",
"marketValue": "15,000,000 €"
},
{
"name": "Claudio Bravo",
"position": "Keeper",
"jerseyNumber": 13,
"dateOfBirth": "1983-04-13",
"nationality": "Chile",
"contractUntil": "2018-06-30",
"marketValue": "15,000,000 €"
}
]
}
I am successfully able to receive data using fetch, the thing which I am unable to figure out is how do I parse the fetched data so that my collection catalons will contain nothing but only the players? i.e. similar to if I had set it up this way:
var catalons = new PlayersCollection(playerModelArray);

You can do this using Backbone's Collection parse method. You simply need to add a parse method to your PlayersCollection prototype definition:
var PlayersCollection = Backbone.Collection.extend({
url: "http://api.football-data.org/v1/teams/81/players",
model: PlayerModel,
parse: function (response) {
return response.players;
}
});

Related

Unable to iterate the response body and manipulate/filter the response object using node JS

I have below code which is going to invoke REST endpoint and return response back. I just tried to print the response.body in the console and It works perfectly fine.
var express = require('express');
var app = express();
var PORT = 8001;
var request = require('request');
var HashMap = require('hashmap');
var endPoint="http://sandbox.dev.amazon.com/idsearch/environment/amazon/";
app.get('/productId/:proId',async (req,res) => {
try
{
var headers ={
"accept":"application/json"
}
var options = {
url:endPoint.concat(req.params.proId),
headers:headers
}
request(options, (error,response,body)=> {
console.log(response.body) // It returned response as below output JSON file
res.send("STATUS CODE : 200");
});
}
catch(error)
{
throw error;
}
});
Output:
{
"<Some dynamic Content>": {
"type": "PROD-ID",
"environment": "amazon",
"tags": [
{
"name": "EC-6S0005704A8324S98020",
"source": "amazonstage2ma_paymentapiplatserv#TOKEN",
"flags": [
"FLAG_DYNAMIC_VALUE",
"FLAG_ID_LOOKUP_SUPPORTED"
]
}
],
"callSummary": [
{
"pool": "slingshotrouter",
"machine": "stage21007",
"apiName": "GET",
"status": "0",
"duration": 13400.0,
"link": "https://www.amazon.qa.pilot.com/Tid-942342192424j2j234"
},
{
"pool": "slingshot",
"machine": "stage21029",
"apiName": "GET",
"status": "1",
"duration": 13368.0,
"link": "https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j234"
},
{
"pool": "devstage_userbridgedomainserv",
"machine": "amazon1int-g_userbridgedomainserv_22",
"apiName": "POST",
"status": "1",
"duration": 15.0,
"link": "https://www.amazon.qa.pilot.com/Tid-02341723424i842424j2j290"
}
],
"partial": false
}
}
The above output contains all the responses with respective Endpoint URL which is expected. But I just want to fetch only the object contains "Status: 1". I'm just wondering that How can I manipulate the response.body object to get the below JSON as output.
Expected Output:
{
"callSummary":[
{
"pool": "slingshot",
"machine": "stage21029",
"apiName": "GET",
"status": "1",
"duration": 13368.0,
"link": "https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j234"
},
{
"pool": "devstage_userbridgedomainserv",
"machine": "amazon1int-g_userbridgedomainserv_22",
"apiName": "POST",
"status": "1",
"duration": 15.0,
"link": "https://www.amazon.qa.pilot.com/Tid-02341723424i842424j2j290"
}
]
}
I just want to iterate the response.body obj and check the status as 1 if it's then I need to fetch all the details and form it as above payload. This is dynamic content but the template format is static.
I tried the below code to iterate the response.body but no luck.
var string = JSON.stringify(response.body);
var objectValue = JSON.parse(string);
var obj = objectValue.callSummary;
console.log(obj.length); // It returned undefined.
Please lead me to achieve this.
To return that json, just
res.json(response.body['<Some dynamic Content>'].callSummary);
Adding some validation and error handling would be a good idea before sending the response.
In case your key is just an example and you never know your first key value, and you always want the values of the first key
res.json(Object.values(response.body)[0].callSummary);
Object.values returns an array, so you can iterate the values if you want manage more than the first one

Extracting data from nested object with AWS ec2.describeInstances in node.js

I am relatively new to JavaScript.
I am trying to extract specific information from AWS about my EC2 instances using describeInstances. Specifically, I want to be able to provide a list of InstanceIds and extract from the resulting object the value of the Tags with Key: "Name". Here is the base code:
// Load the SDK for JavaScript
var AWS = require('aws-sdk');
// Load credentials and set region from JSON file
AWS.config.loadFromPath('./.aws/config.json');
// Create EC2 service object
var ec2 = new AWS.EC2({apiVersion: '2016-11-15'});
var params = {
DryRun: false,
InstanceIds: ['i-0be50217a4028a044', 'i-08b83c1c428e9a1d2']
};
ec2.describeInstances(params, function(err, data) {
if (err) {
console.log("Error", err.stack);
} else {
console.log("Success", JSON.stringify(data));
}
});
Upon running this code, a large, hairy, and nested object is returned. The JSON.stringify() version of this is shown here:
{
"Reservations": [{
"ReservationId": "r-04e32387e546387ba",
"OwnerId": "543800113692",
"Groups": [],
"Instances": [{
"InstanceId": "i-08b83c1c428e9a1d2",
"ImageId": "ami-8aa998ea",
"State": {
"Code": 16,
"Name": "running"
},
"PrivateDnsName": "ip-10-77-113-210.us-west-2.compute.internal",
"PublicDnsName": "ec2-35-165-200-222.us-west-2.compute.amazonaws.com",
"StateTransitionReason": "",
"KeyName": "Security1",
"AmiLaunchIndex": 0,
"ProductCodes": [],
"InstanceType": "t2.micro",
"LaunchTime": "2017-02-14T14:59:11.000Z",
"Placement": {
"AvailabilityZone": "us-west-2b",
"GroupName": "",
"Tenancy": "default"
},
"Monitoring": {
"State": "disabled"
},
"SubnetId": "subnet-228da755",
"VpcId": "vpc-af0f0dca",
"PrivateIpAddress": "10.77.113.210",
"PublicIpAddress": "35.165.200.222",
"Architecture": "x86_64",
"RootDeviceType": "ebs",
"RootDeviceName": "/dev/sda1",
"BlockDeviceMappings": [{
"DeviceName": "/dev/sda1",
"Ebs": {
"VolumeId": "vol-00e55d6bf114bfcaa0",
"Status": "attached",
"AttachTime": "2017-02-09T15:37:34.000Z",
"DeleteOnTermination": true
}
}],
"VirtualizationType": "hvm",
"ClientToken": "vOiiS1486654656072",
"Tags": [{
"Key": "Name",
"Value": "Fenris"
}],
"SecurityGroups": [{
"GroupName": "launch-wizard-2",
"GroupId": "sg-2312072c"
}],
"SourceDestCheck": true,
"Hypervisor": "xen",
"EbsOptimized": false
}]
}, {
"ReservationId": "r-0bbcb12e5c1162c23",
"OwnerId": "543800113692",
"Groups": [],
"Instances": [{
"InstanceId": "i-0be50217a40028a044",
"ImageId": "ami-8ba011ea",
"State": {
"Code": 80,
"Name": "stopped"
},
"PrivateDnsName": "ip-10-77-118-17.us-west-2.compute.internal",
"PublicDnsName": "",
"StateTransitionReason": "User initiated (2016-12-05 16:49:45 GMT)",
"KeyName": "Security3",
"AmiLaunchIndex": 0,
"ProductCodes": [],
"InstanceType": "t2.medium",
"LaunchTime": "2016-12-02T15:50:08.000Z",
"Placement": {
"AvailabilityZone": "us-west-2b",
"GroupName": "",
"Tenancy": "default"
},
"Monitoring": {
"State": "disabled"
},
"SubnetId": "subnet-228da700",
"VpcId": "vpc-af0f1ccb",
"PrivateIpAddress": "10.77.118.17",
"StateReason": {
"Code": "Client.UserInitiatedShutdown",
"Message": "Client.UserInitiatedShutdown: User initiated shutdown"
},
"Architecture": "x86_64",
"RootDeviceType": "ebs",
"RootDeviceName": "/dev/sda1",
"BlockDeviceMappings": [{
"DeviceName": "/dev/sda1",
"Ebs": {
"VolumeId": "vol-1c211ac8",
"Status": "attached",
"AttachTime": "2016-11-22T01:54:52.000Z",
"DeleteOnTermination": true
}
}],
"VirtualizationType": "hvm",
"ClientToken": "RQbhg1479762230132",
"Tags": [{
"Key": "Name",
"Value": "Heimdall"
}, {
"Key": "Type",
"Value": "Product Dev"
}],
"SecurityGroups": [{
"GroupName": "LinuxAPIdev",
"GroupId": "sg-5ea11777"
}],
"SourceDestCheck": true,
"Hypervisor": "xen",
"EbsOptimized": false
}]
}]
}
This is way more info than I need or want. I want to find a way to get only the values of Reservations.Instances.Tags.Value from the Reservations.Instances.Tags.Name key.
I thought that just writing it that way would work. But strangely, I can't seem to access the Reservations.Instances object at all:
// Load the SDK for JavaScript
var AWS = require('aws-sdk');
// Load credentials and set region from JSON file
AWS.config.loadFromPath('./.aws/config.json');
// Create EC2 service object
var ec2 = new AWS.EC2({apiVersion: '2016-11-15'});
var params = {
DryRun: false,
InstanceIds: ['i-0be5987a41191a044', 'i-08b83c3fc28e9a1d2']
};
// call EC2 to retrieve policy for selected bucket
ec2.describeInstances(params, function(err, data) {
if (err) {
console.log("Error", err.stack);
} else {
console.log("Success", JSON.stringify(data.Reservations.Instances));
}
});
This results in:
Success undefined
What am I doing wrong? How do I access the lower level of data within Instances? It is obviously there... it shows up in JSON.stringify(), but clearly I don't have the right protocol for extracting it.
(P.S. Because of AWS credentials, you won't be able to run my code without minor changes. You'll need to reference your own credentials, and InstanceIds from your own EC2 instances.)
Reservations, Instances and Tags All are arrays that''s why :
Reservations[0].Instances[0].Tags[0].Value
// value of 1ˢᵗ tag of 1ˢᵗ instance of 1ˢᵗ reservation
and Not
Reservations.Instances.Tags.Value
Within your describeInstances() method, you can simply use
// for InstanceId : "i-08b83c1c428e9a1d2"
data.Reservations[0].Instances[0].Tags[0].Value;
// and for InstanceId : "i-0be50217a40028a044"
data.Reservations[1].Instances[0].Tags[0].Value;
You can anyway create a function, if required, to return the tags value if the object structure is known.

Having trouble using data retrieved with json in javascript, cannot sort the array

I am trying to sort out the data I retrieved from an api with javascript.
Code :
function getResults() {
var url = $.getJSON("http://api.api.com&leagues=SOCENGPRE&lang=en&format=jsonp&callback=?", function(jsondata){;
for(var i = 0; i < jsondata.length; i++)
for(var id in jsondata[i]) {
console.log("ID - " + id);
console.log("TEAM - " + jsondata[i][id].home_team);
}
});
}
Example of data retrieved :
{
"SOCENGPRE": {
"league_name": "Barclays Premier League",
"league_phid": null,
"league_type": null,
"fixtures": [
{
"id": "64714",
"code": "SOCENGPRE",
"event_slug": "west_ham-tottenham-1401290",
"home_team": "West Ham",
"away_team": "Tottenham",
},
{
"id": "64711",
"code": "SOCENGPRE",
"event_slug": "manchester_u-sunderland-1401286",
"home_team": "Manchester U",
"away_team": "Sunderland"
}
But using my code I cannot seem to get the results I am wanting.
I want to print out every games ID and Home Team. Any insights on why is my code not working? Thank you very much in advance!
UPDATE: I have removed the extra semi-colon but it's still not printing the data for me.
UPDATE 2: Regarding the requests for the URL. When I call it in a browser I get this huge result
?({"SOCENGPRE":{"league_name":"Barclays Premier League","league_phid":null,"league_type":null,"fixtures":[{"id":"64714","code":"SOCENGPRE","event_slug":"west_ham-tottenham-1401290","start":"1399117500","home_team":"West Ham","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t523.png","home_team_short":"","away_team":"Tottenham","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t498.png","away_team_short":"","phid":null},{"id":"64711","code":"SOCENGPRE","event_slug":"manchester_u-sunderland-1401286","start":"1399125600","home_team":"Manchester U","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t20790.png","home_team_short":"Man U","away_team":"Sunderland","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t382.png","away_team_short":"","phid":null},{"id":"64712","code":"SOCENGPRE","event_slug":"stoke-fulham-1401288","start":"1399125600","home_team":"Stoke","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t389.png","home_team_short":"","away_team":"Fulham","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t379.png","away_team_short":"","phid":null},{"id":"64706","code":"SOCENGPRE","event_slug":"aston_villa-hull-1401282","start":"1399125600","home_team":"Aston Villa","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t380.png","home_team_short":"","away_team":"Hull","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t511.png","away_team_short":"Hull","phid":null},{"id":"64710","code":"SOCENGPRE","event_slug":"newcastle-cardiff-1401287","start":"1399125600","home_team":"Newcastle","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t385.png","home_team_short":"","away_team":"Cardiff","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t524.png","away_team_short":"","phid":null},{"id":"64713","code":"SOCENGPRE","event_slug":"swansea-southampton-1401289","start":"1399125600","home_team":"Swansea","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t384.png","home_team_short":"Swansea","away_team":"Southampton","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t8482.png","away_team_short":"","phid":null},{"id":"64709","code":"SOCENGPRE","event_slug":"everton-manchester_c-1401285","start":"1399134600","home_team":"Everton","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t499.png","home_team_short":"","away_team":"Manchester C","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t383.png","away_team_short":"Man C","phid":null},{"id":"64707","code":"SOCENGPRE","event_slug":"arsenal-west_bromwich-1401281","start":"1399206600","home_team":"Arsenal","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t30773.png","home_team_short":"","away_team":"West Bromwich","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t816.png","away_team_short":"West Brom","phid":null},{"id":"64705","code":"SOCENGPRE","event_slug":"chelsea-norwich-1401283","start":"1399215600","home_team":"Chelsea","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t497.png","home_team_short":"","away_team":"Norwich","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t1438.png","away_team_short":"","phid":null},{"id":"64708","code":"SOCENGPRE","event_slug":"crystal_palace-liverpool-1401284","start":"1399316400","home_team":"Crystal Palace","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t518.png","home_team_short":"C. Palace","away_team":"Liverpool","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t381.png","away_team_short":"","phid":null},{"id":"64679","code":"SOCENGPRE","event_slug":"manchester_u-hull-1401252","start":"1399401900","home_team":"Manchester U","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t20790.png","home_team_short":"Man U","away_team":"Hull","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t511.png","away_team_short":"Hull","phid":null},{"id":"64630","code":"SOCENGPRE","event_slug":"manchester_c-aston_villa-1401198","start":"1399488300","home_team":"Manchester C","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t383.png","home_team_short":"Man C","away_team":"Aston Villa","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t380.png","away_team_short":"","phid":null},{"id":"64621","code":"SOCENGPRE","event_slug":"sunderland-west_bromwich-1401189","start":"1399488300","home_team":"Sunderland","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t382.png","home_team_short":"","away_team":"West Bromwich","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t816.png","away_team_short":"West Brom","phid":null},{"id":"64719","code":"SOCENGPRE","event_slug":"manchester_c-west_ham-1401296","start":"1399816800","home_team":"Manchester C","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t383.png","home_team_short":"Man C","away_team":"West Ham","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t523.png","away_team_short":"","phid":null},{"id":"64717","code":"SOCENGPRE","event_slug":"liverpool-newcastle-1401295","start":"1399816800","home_team":"Liverpool","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t381.png","home_team_short":"","away_team":"Newcastle","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t385.png","away_team_short":"","phid":null},{"id":"64720","code":"SOCENGPRE","event_slug":"norwich-arsenal-1401297","start":"1399816800","home_team":"Norwich","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t1438.png","home_team_short":"","away_team":"Arsenal","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t30773.png","away_team_short":"","phid":null},{"id":"64715","code":"SOCENGPRE","event_slug":"fulham-crystal_palace-1401293","start":"1399816800","home_team":"Fulham","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t379.png","home_team_short":"","away_team":"Crystal Palace","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t518.png","away_team_short":"C. Palace","phid":null},{"id":"64722","code":"SOCENGPRE","event_slug":"sunderland-swansea-1401299","start":"1399816800","home_team":"Sunderland","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t382.png","home_team_short":"","away_team":"Swansea","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t384.png","away_team_short":"Swansea","phid":null},{"id":"64723","code":"SOCENGPRE","event_slug":"tottenham-aston_villa-1401300","start":"1399816800","home_team":"Tottenham","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t498.png","home_team_short":"","away_team":"Aston Villa","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t380.png","away_team_short":"","phid":null},{"id":"64724","code":"SOCENGPRE","event_slug":"west_bromwich-stoke-1401301","start":"1399816800","home_team":"West Bromwich","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t816.png","home_team_short":"West Brom","away_team":"Stoke","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t389.png","away_team_short":"","phid":null},{"id":"64718","code":"SOCENGPRE","event_slug":"hull-everton-1401294","start":"1399816800","home_team":"Hull","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t511.png","home_team_short":"Hull","away_team":"Everton","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t499.png","away_team_short":"","phid":null},{"id":"64721","code":"SOCENGPRE","event_slug":"southampton-manchester_u-1401298","start":"1399816800","home_team":"Southampton","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t8482.png","home_team_short":"","away_team":"Manchester U","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t20790.png","away_team_short":"Man U","phid":null},{"id":"64716","code":"SOCENGPRE","event_slug":"cardiff-chelsea-1401292","start":"1399816800","home_team":"Cardiff","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t524.png","home_team_short":"","away_team":"Chelsea","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t497.png","away_team_short":"","phid":null}]}});
Link to pastebin for easier reading of the data
Change your getResults function to be called after the JSON has been parsed, like so:
var myDataVar;
$.ajax({
url: "URL to JSON file here",
dataType: "text", //If you get an error here, change the type to "text"
success: function (data) {
myDataVar = $.parseJSON(data);
getResults();
}
});
The above code will save the JSON file's parsed data into a single variable.
It will then call a function to get the results, being this function:
function getResults() {
var fixturesLength = myDataVar.SOCENGPRE.fixtures.length - 1;
for (var i = 0; i <= fixturesLength; i++) {
console.log(myDataVar.SOCENGPRE.fixtures[i].id);
}
}
The above loop will print to the console every one of your fixtures ID's.
Test data used:
{
"SOCENGPRE": {
"league_name": "Barclays Premier League",
"league_phid": null,
"league_type": null,
"fixtures": [{
"id": "64714",
"code": "SOCENGPRE",
"event_slug": "west_ham-tottenham-1401290",
"start": "1399117500",
"home_team": "West Ham",
"home_team_phid": null,
"home_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t523.png",
"home_team_short": "",
"away_team": "Tottenham",
"away_team_phid": null,
"away_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t498.png",
"away_team_short": "",
"phid": null
}, {
"id": "64711",
"code": "SOCENGPRE",
"event_slug": "manchester_u-sunderland-1401286",
"start": "1399125600",
"home_team": "Manchester U",
"home_team_phid": null,
"home_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t20790.png",
"home_team_short": "Man U",
"away_team": "Sunderland",
"away_team_phid": null,
"away_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t382.png",
"away_team_short": "",
"phid": null
}, {
"id": "64712",
"code": "SOCENGPRE",
"event_slug": "stoke-fulham-1401288",
"start": "1399125600",
"home_team": "Stoke",
"home_team_phid": null,
"home_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t389.png",
"home_team_short": "",
"away_team": "Fulham",
"away_team_phid": null,
"away_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t379.png",
"away_team_short": "",
"phid": null
}]
}
}
Console results:
64714
64711
64712

Backbone JS: how to parse JSON response with dynamic named objects

I'm trying to parse the following JSON response to a Backbone.Collection:
{
"16": {
"_id": "16",
"lastname": ...,
...
},
"17": {
"_id": "17",
"lastname": ...,
...
},
...
},
"39": {
"_id": "39"
"lastname": ...,
...
}
}
How could one parse the set of name/value pairs ("_id", "lastname", ...)?
you need to return an array in order to parse it to a collection.
so in your parse function:
parse: function (response) {
return _.map(response, function(obj) {
return obj;
});
}
make sure in your model, you have defined the correct idAttribute since you are using non-standard id name:
var YourModel = Backbone.Model.extend({
idAttribute: "_id"
});

Understanding JSON and displaying

I have the following ajax request...
Ajax
function initUpdate()
{
var id = $(this).attr('id').split('_')[1];
//grab id from link update_xxxx
//get all gallery information
$.ajax(
{
type: 'POST',
url: 'ajax/update',
data: {"id": id},
dataType: 'json',
success: function(json)
{
//query was successful now populate form
$("input[name='galleryName']").val(/*what goes here?*/);
}
});
}
That returns the following data
{
"selected_gallery": [
{
"id": "4004",
"name": "Album Proofer Sample Gallery",
"clientRef": "205",
"clientName": "Mike "
}
]
}
How would I access "name" to insert in the val()?
Thanks!
What have you tried? I would think you could get to it via:
json.selected_gallery[0].name
selected_gallery is a JavaScript array, so you would access the first item in the collection using [0] in order access the first item's properties.
UPDATE
You could access other items in the array if they existed:
{
"selected_gallery": [
{
"id": "4004",
"name": "Album Proofer Sample Gallery",
"clientRef": "205",
"clientName": "Mike "
},
{
"id": "5005",
"name": "blah",
"clientRef": "405",
"clientName": "Dave "
},
{
"id": "6006",
"name": "boo",
"clientRef": "605",
"clientName": "Doug"
}
]
}
To get the second item in the array, you'd reference it as:
json.selected_gallery[1].name (or id or clientRef or ...). You can get to the third item via json.selected_gallery[2].name.
Hope this helps.

Categories