Javascript, issues reading CSV file (original file is JSON) - javascript

I am learning JS and I'm having an issue.
I have a sample data set: miserables.js that its in this format:
var miserables = {
nodes:[
{nodeName:"Myriel", group:1},
{nodeName:"Napoleon", group:1},
.....
{nodeName:"Mme. Hucheloup", group:8}
],
links:[
{source:1, target:0, value:1},
{source:2, target:0, value:8},
.....
{source:76, target:58, value:1}
]
};
and I'm reading it, just with this
<script type="text/javascript" src="./miserables.js"></script>
and it works perfect.
The issue comes when I want to read directly that information from two csv files:
links1.csv
source target weight
Myriel Napoleon 3
Napoleon Mme. Hucheloup 2
Napoleon Myriel 23
Mme. Hucheloup Myriel 4
... ... ...
nodes2.csv
node group description
Myriel A family A
Napoleon C family B
Mme. Hucheloup C family C
... ... ...
The script that I'm using to do so its as follows, which I can make it work:
<script>
$(document).ready(function () {
var links = [], nodes = [], links_backup = [];
d3.csv('./links1.csv',function(links_csv) {
return {
source:links_csv.source,
target:links_csv.target,
strength:links_csv.strength,
year:links_csv.year,
type:links_csv.type,
}
},function(csv_data) {
$.each(csv_data,function (idx,row) {
links.push(row)
links_backup.push(row)
})
});
d3.csv('./nodes2.csv',function (nodes_csv) {
var row = {
node:nodes_csv.node,
group:nodes_csv.group,
description_n4:nodes_csv.description_n4,
}
if (nodes_csv.hasOwnProperty('weight')) {
row.weight = nodes_csv.weight
}
return row
},function (data) {
var node_groups = {}
$.each(data,function (idx,row) {
nodes.push(row)
if (!node_groups.hasOwnProperty(row.group)) {
node_groups[row.group] = {
fill: getRandomColor()
}
}
})
})

Related

access object in parsed nested JSON in Google Apps Script

I am trying to access the student tags array which has an object inside of it (student_tags:tag:"do not contact") Can someone please help me with the syntax on getting this data? I am pretty sure my syntax in retrieving this array is incorrect.
JSON Data being fetched:
{
"id":"e90c4c93-207c-49f7-89c4-eb85b3315dd5",
"created_by_user_id":"8560ed12-2858-4237-bea2-3dcab82637d3",
"date_created":"2019-08-06T22:54:59.583257+00:00",
"person_number":5973,
"first_name":"Test",
"middle_name":"James",
"last_name":"Cook",
"birth_name":null,
"email":"test#gmail.com",
"alt_email":null,
"facebook_url":null,
"linkedin_url":"https://www.linkedin.com/in/test-burns-273a5165/",
"gender":"Male",
"phone_numbers":[
{
"phone_type":"Mobile",
"number":"449288809"
},
{
"phone_type":"Home",
"number":"93938289"
}
],
"is_no_contact":false,
"is_client":false,
"student_detail":{
"onboarding_student_setting_id":"e189187a-cc91-43c6-ac44-635328b1e95a",
"student_onboarding_setting":{
"id":"e189187a-cc91-43c6-ac44-635328b1e95a",
"created_by_user_id":"562a63a2-e24e-4ff7-8358-dfb74ed6c70a",
"title":"High School On-boarding Process",
"description":"High School On-boarding Process",
"is_default":false,
"onboarding_steps":[
{
"step_id":"9cd30560-1c3c-4382-b8a2-505e78b9ce4d",
"set_tags":[
"Student Tag"
],
"set_to_status":"Potential",
"title":"Contact",
"short_title":"Contact",
"is_attachment_required":null
},
{
"step_id":"e6f90546-a516-416c-a880-9adc10358f1d",
"set_tags":[
],
"set_to_status":"Pipeline",
"title":"Program Orientation",
"short_title":"PO",
"is_attachment_required":null
},
{
"step_id":"8660df59-ddd8-4182-b6ca-c44e3de70969",
"set_tags":[
],
"set_to_status":"Confirmed",
"title":"Parental Consent",
"short_title":"Parental Consent",
"is_attachment_required":true
}
],
"is_disabled":false
},
"student_onboarding_history":[
],
"onboarding_steps_complete":null,
"onboarding_percent":null,
"graduating_student_setting_id":null,
"student_graduating_setting":null,
"student_graduating_history":[
],
"graduating_steps_complete":null,
"graduating_percent":null,
"is_active":true,
"date_deactivated":"2019-08-09T03:36:57.977584",
"deactivated_person_id":"562a63a2-e24e-4ff7-8358-dfb74ed6c70a",
"deactviated_notes":null,
"student_status":"Pipeline",
"language_group":null,
"heritage":null,
"date_ics_set":"2019-08-08T04:28:48.832170",
"ics_by_person_id":"562a63a2-e24e-4ff7-8358-dfb74ed6c70a",
"ics_status":"Active",
"ics_id":null,
"ics_start":null,
"ics_end":null,
"ics_notes":null,
"student_tags":[
{
"tag":"Do not contact",
"date_added":"2019-08-13 06:06:13.012817"
}
],
"student_source":"Other",
"date_of_birth":"2019-08-07",
"semester_number_start":null,
"semester_year_start":null,
"semester_number_end":null,
"semester_year_end":null,
"location_address":{
"line_1":"34 Adelaide Avenue",
"line_2":"",
"suburb":"east lindfield",
"postcode":"2322",
"state":"",
"country_code":"AU",
"location_description":"east lindfield, ",
"formatted_location":null,
"latitude":"-33.7691871",
"longitude":"151.1863407"
},
"emergency_first_name":"Someone",
"emergency_last_name":"",
"emergency_phone_numbers":[
],
"emergency_address":{
"line_1":"hi",
"line_2":"",
"suburb":"willoughby",
"postcode":"4154",
"state":"NSW",
"country_code":"AU",
"location_description":"willoughby, NSW",
"formatted_location":null,
"latitude":"-33.804179",
"longitude":"151.2042376"
},
"emergency_relationship":"Auntie",
"university":null,
"campus":null,
"degree_pool_id":[
],
"degree":null,
"degree_major":null,
"high_school":"School",
"high_school_complete":null,
"is_travel_required":null,
"date_alumni_set":null,
"alumni_set_by_person_id":null,
"alumni_company":null,
"alumni_job_title":null,
"alumni_city":null,
"alumni_state":null,
"alumni_country_code":null,
"alumni_notes":null,
"is_at_risk":null,
"date_at_risk_set":null,
"at_risk_by_person_id":null,
"at_risk_context":null,
"at_risk_reasons":null,
"at_risk_semester":null,
"at_risk_year":null,
"at_risk_notes":null,
"quick_notes":null,
"cv_url":null,
"public_summary":null,
"public_profile":null,
"is_graduating":null,
"graduating_by_person_id":null,
"graduating_semester":null,
"graduating_year":null,
"graduating_notes":null,
"advisor_users":[
{
"date_created":"2019-08-06T22:54:59.582970+00:00",
"is_primary":true,
"advisor_person_id":"8560ed12-2858-4237-bea2-3dcab82637d3"
}
]
},
"contact_detail":{
"company_id":null,
"contact_tags":null,
"location_address":{
"line_1":null,
"line_2":null,
"suburb":null,
"postcode":null,
"state":null,
"country_code":null,
"location_description":null,
"formatted_location":null,
"latitude":null,
"longitude":null
},
"job_title":null,
"quick_notes":null,
"is_primary":null,
"is_billing":null,
"is_student_contact":null,
"advisor_users":null
},
"current_placements":null,
"previous_placements":null
}
The function returning the JSON response:
var url = "http://api.com/v1/";
var response = UrlFetchApp.fetch(url, options);
var message = response.getContentText();
var code = response.getResponseCode();
Logger.log(message)
var tags = message["student_tags"][0]
Logger.log(tags)
In response to 'would you know how to use the key/value loop to access the same student tag value ("Do not contact")?', I'm not sure I understand the question, but the below code may be a good place to start. Let me know if I'm way off track...
var tags = message.student_detail.student_tags,
i = 0,
len = tags.length;
for (i; i < len; i++) {
var obj = tags[i];
for (a in obj) {
console.log(a, obj[a])
}
}

How To Loop and Load Section of JSON to New Array

I am getting some dynamic data from Ajax call in JSON format on
var out;
request.done(function( data ) {
out = data;
console.log(out);
});
which looks like
{
"seq":"1",
"node":"1407",
"edge":"1721",
"cost":"0.00155228618815934",
"st_astext":"MULTILINESTRING((-124.339494 49.3269419000001,-124.3387254 49.3269805,-124.338669 49.3270201,-124.3386158 49.3270832000001,-124.3386343 49.3274121000001,-124.3386975 49.3274896,-124.3390742 49.3276439000001,-124.3394701 49.3277238000001,-124.339726 49.3277574000001,-124.3398638 49.3277496000001,-124.3399475 49.3277140000001,-124.3400263 49.3276270000001,-124.3402516 49.3272857000001,-124.340277 49.3271520000001,-124.3402715 49.3270367000001,-124.3402042 49.3269591000001,-124.3401021 49.3269305000001,-124.339494 49.3269419000001))"
}{
"seq":"2",
"node":"2459",
"edge":"43870",
"cost":"0.0014795249102581",
"st_astext":"MULTILINESTRING((-123.4051866 48.4191865000001,-123.4053714 48.4191387000001,-123.405405 48.4190178000001,-123.4050125 48.4186474000001,-123.4047663 48.4185377000001,-123.4045437 48.4185367000001,-123.4044758 48.4185937,-123.4043546 48.4189586000001,-123.404408 48.4190429000001,-123.4051866 48.4191865000001))"
}{
"seq":"3",
"node":"14962",
"edge":"15633",
"cost":"0.00144452021471863",
"st_astext":"MULTILINESTRING((-124.2005178 48.8657682,-124.2008549 48.8656748000001,-124.2011903 48.8656273,-124.2020436 48.8656722000001,-124.2029403 48.8658963,-124.2033335 48.8659029,-124.2034588 48.8658654000001,-124.2034906 48.8658182,-124.2034447 48.8657724,-124.203297 48.8657185000001,-124.203148 48.8656980000001,-124.2027598 48.865705,-124.20221 48.8655579000001,-124.2017332 48.8654932000001,-124.200973 48.8654362,-124.2006816 48.8654025000001,-124.200004 48.8651794,-124.1997069 48.8650816000001,-124.1995273 48.8650453000001,-124.1992556 48.8650290000001,-124.1988955 48.8649418000001,-124.1987556 48.8649332000001,-124.1986996 48.8649719000001,-124.1986801 48.8650336000001,-124.1986764 48.8650454,-124.1987314 48.8651373000001,-124.1988681 48.8651927000001,-124.1992515 48.8652406000001,-124.1995975 48.8653437,-124.2000068 48.8655325,-124.2005013 48.8657606,-124.2005178 48.8657682))"
}{
"seq":"4",
"node":"13891",
"edge":"13862",
"cost":"0.00076542396749831",
"st_astext":"MULTILINESTRING((-124.4606302 49.3438327000001,-124.4605727 49.3436995000001,-124.4604416 49.3435897000001,-124.4602789 49.3435198000001,-124.4601008 49.3434993000001,-124.4599664 49.3435289000001,-124.4598809 49.3436195,-124.4598941 49.3441714000001,-124.4599637 49.3442309000001,-124.4600623 49.3442440000001,-124.4601711 49.3441961,-124.4606302 49.3438327000001))"
}{
"seq":"5",
"node":"3684",
"edge":"28825",
"cost":"0.00117904724673861",
"st_astext":"MULTILINESTRING((-123.3495787 48.4045938,-123.3496211 48.4041484000001,-123.3493846 48.4033146,-123.3492248 48.4032068000001,-123.3490655 48.4031857000001,-123.3489141 48.4032153000001,-123.3486746 48.4033022,-123.3486286 48.4034498,-123.3494207 48.4043084,-123.3495787 48.4045938))"
}{
"seq":"6",
"node":"12168",
"edge":"11270",
"cost":"0.00109953281896407",
"st_astext":"MULTILINESTRING((-123.4652201 48.4475155000001,-123.4648358 48.4482124,-123.4650847 48.4482788,-123.4654424 48.4475732000001,-123.4652201 48.4475155000001))"
}
now I need to load the "st_astext":"MULTILINESTRING of each seq to arrays of arry like
var paths = [
[
[-124.339494,49.3269419000001],
[-124.3387254,49.3269805],
[-124.338669,49.3270201],
...
],
[
[-123.4051866, 48.4191865000001],
[-123.4053714, 48.4191387000001],
[-123.405405, 48.4190178000001],
....
]
];
To accomplish this, you can strip out the "MULTILINE..." portion of your string, and then split that string on a comma to get each set of coordinates. From there, you can split on the space separating the coordinates, and coerce to a Number. Like so:
var data = [{
"seq":"1",
"node":"1407",
"edge":"1721",
"cost":"0.00155228618815934",
"st_astext":"MULTILINESTRING((-124.339494 49.3269419000001,-124.3387254 49.3269805,-124.338669 49.3270201,-124.3386158 49.3270832000001,-124.3386343 49.3274121000001,-124.3386975 49.3274896,-124.3390742 49.3276439000001,-124.3394701 49.3277238000001,-124.339726 49.3277574000001,-124.3398638 49.3277496000001,-124.3399475 49.3277140000001,-124.3400263 49.3276270000001,-124.3402516 49.3272857000001,-124.340277 49.3271520000001,-124.3402715 49.3270367000001,-124.3402042 49.3269591000001,-124.3401021 49.3269305000001,-124.339494 49.3269419000001))"
},{
"seq":"2",
"node":"2459",
"edge":"43870",
"cost":"0.0014795249102581",
"st_astext":"MULTILINESTRING((-123.4051866 48.4191865000001,-123.4053714 48.4191387000001,-123.405405 48.4190178000001,-123.4050125 48.4186474000001,-123.4047663 48.4185377000001,-123.4045437 48.4185367000001,-123.4044758 48.4185937,-123.4043546 48.4189586000001,-123.404408 48.4190429000001,-123.4051866 48.4191865000001))"
},{
"seq":"3",
"node":"14962",
"edge":"15633",
"cost":"0.00144452021471863",
"st_astext":"MULTILINESTRING((-124.2005178 48.8657682,-124.2008549 48.8656748000001,-124.2011903 48.8656273,-124.2020436 48.8656722000001,-124.2029403 48.8658963,-124.2033335 48.8659029,-124.2034588 48.8658654000001,-124.2034906 48.8658182,-124.2034447 48.8657724,-124.203297 48.8657185000001,-124.203148 48.8656980000001,-124.2027598 48.865705,-124.20221 48.8655579000001,-124.2017332 48.8654932000001,-124.200973 48.8654362,-124.2006816 48.8654025000001,-124.200004 48.8651794,-124.1997069 48.8650816000001,-124.1995273 48.8650453000001,-124.1992556 48.8650290000001,-124.1988955 48.8649418000001,-124.1987556 48.8649332000001,-124.1986996 48.8649719000001,-124.1986801 48.8650336000001,-124.1986764 48.8650454,-124.1987314 48.8651373000001,-124.1988681 48.8651927000001,-124.1992515 48.8652406000001,-124.1995975 48.8653437,-124.2000068 48.8655325,-124.2005013 48.8657606,-124.2005178 48.8657682))"
},{
"seq":"4",
"node":"13891",
"edge":"13862",
"cost":"0.00076542396749831",
"st_astext":"MULTILINESTRING((-124.4606302 49.3438327000001,-124.4605727 49.3436995000001,-124.4604416 49.3435897000001,-124.4602789 49.3435198000001,-124.4601008 49.3434993000001,-124.4599664 49.3435289000001,-124.4598809 49.3436195,-124.4598941 49.3441714000001,-124.4599637 49.3442309000001,-124.4600623 49.3442440000001,-124.4601711 49.3441961,-124.4606302 49.3438327000001))"
},{
"seq":"5",
"node":"3684",
"edge":"28825",
"cost":"0.00117904724673861",
"st_astext":"MULTILINESTRING((-123.3495787 48.4045938,-123.3496211 48.4041484000001,-123.3493846 48.4033146,-123.3492248 48.4032068000001,-123.3490655 48.4031857000001,-123.3489141 48.4032153000001,-123.3486746 48.4033022,-123.3486286 48.4034498,-123.3494207 48.4043084,-123.3495787 48.4045938))"
},{
"seq":"6",
"node":"12168",
"edge":"11270",
"cost":"0.00109953281896407",
"st_astext":"MULTILINESTRING((-123.4652201 48.4475155000001,-123.4648358 48.4482124,-123.4650847 48.4482788,-123.4654424 48.4475732000001,-123.4652201 48.4475155000001))"
}];
var paths = data.map(elem => {
var coordsBegin = elem.st_astext.split("((")[1];
var coords = coordsBegin.split("))")[0];
return coords.split(",").map(coord => coord.split(" ").map(Number));
});
console.log(paths);
Assuming the initial data structure is an array of objects, you can loop through it and generate the desired output with Array.prototype.map
const data = [{
"seq":"1",
"node":"1407",
"edge":"1721",
"cost":"0.00155228618815934",
"st_astext":"MULTILINESTRING((-124.339494 49.3269419000001,-124.3387254 49.3269805,-124.338669 49.3270201,-124.3386158 49.3270832000001,-124.3386343 49.3274121000001,-124.3386975 49.3274896,-124.3390742 49.3276439000001,-124.3394701 49.3277238000001,-124.339726 49.3277574000001,-124.3398638 49.3277496000001,-124.3399475 49.3277140000001,-124.3400263 49.3276270000001,-124.3402516 49.3272857000001,-124.340277 49.3271520000001,-124.3402715 49.3270367000001,-124.3402042 49.3269591000001,-124.3401021 49.3269305000001,-124.339494 49.3269419000001))"
}, {
"seq":"2",
"node":"2459",
"edge":"43870",
"cost":"0.0014795249102581",
"st_astext":"MULTILINESTRING((-123.4051866 48.4191865000001,-123.4053714 48.4191387000001,-123.405405 48.4190178000001,-123.4050125 48.4186474000001,-123.4047663 48.4185377000001,-123.4045437 48.4185367000001,-123.4044758 48.4185937,-123.4043546 48.4189586000001,-123.404408 48.4190429000001,-123.4051866 48.4191865000001))"
}, {
"seq":"3",
"node":"14962",
"edge":"15633",
"cost":"0.00144452021471863",
"st_astext":"MULTILINESTRING((-124.2005178 48.8657682,-124.2008549 48.8656748000001,-124.2011903 48.8656273,-124.2020436 48.8656722000001,-124.2029403 48.8658963,-124.2033335 48.8659029,-124.2034588 48.8658654000001,-124.2034906 48.8658182,-124.2034447 48.8657724,-124.203297 48.8657185000001,-124.203148 48.8656980000001,-124.2027598 48.865705,-124.20221 48.8655579000001,-124.2017332 48.8654932000001,-124.200973 48.8654362,-124.2006816 48.8654025000001,-124.200004 48.8651794,-124.1997069 48.8650816000001,-124.1995273 48.8650453000001,-124.1992556 48.8650290000001,-124.1988955 48.8649418000001,-124.1987556 48.8649332000001,-124.1986996 48.8649719000001,-124.1986801 48.8650336000001,-124.1986764 48.8650454,-124.1987314 48.8651373000001,-124.1988681 48.8651927000001,-124.1992515 48.8652406000001,-124.1995975 48.8653437,-124.2000068 48.8655325,-124.2005013 48.8657606,-124.2005178 48.8657682))"
}, {
"seq":"4",
"node":"13891",
"edge":"13862",
"cost":"0.00076542396749831",
"st_astext":"MULTILINESTRING((-124.4606302 49.3438327000001,-124.4605727 49.3436995000001,-124.4604416 49.3435897000001,-124.4602789 49.3435198000001,-124.4601008 49.3434993000001,-124.4599664 49.3435289000001,-124.4598809 49.3436195,-124.4598941 49.3441714000001,-124.4599637 49.3442309000001,-124.4600623 49.3442440000001,-124.4601711 49.3441961,-124.4606302 49.3438327000001))"
}, {
"seq":"5",
"node":"3684",
"edge":"28825",
"cost":"0.00117904724673861",
"st_astext":"MULTILINESTRING((-123.3495787 48.4045938,-123.3496211 48.4041484000001,-123.3493846 48.4033146,-123.3492248 48.4032068000001,-123.3490655 48.4031857000001,-123.3489141 48.4032153000001,-123.3486746 48.4033022,-123.3486286 48.4034498,-123.3494207 48.4043084,-123.3495787 48.4045938))"
}, {
"seq":"6",
"node":"12168",
"edge":"11270",
"cost":"0.00109953281896407",
"st_astext":"MULTILINESTRING((-123.4652201 48.4475155000001,-123.4648358 48.4482124,-123.4650847 48.4482788,-123.4654424 48.4475732000001,-123.4652201 48.4475155000001))"
}];
var paths = data.map(({st_astext}) => {
const [ _ ,numsStr ] = st_astext.match(/\(\((.*)\)\)/);
const arr = numsStr.split(',').map(pair => pair.split(' ').map(Number))
return arr;
});
console.log(paths);

Add item to array Angular

I have a table with these fields: product, lot, input1, input2. You can clone a line, and you can add a new line.
What I want to do is that for each row you can add a new Lot created by a "number" and by "id" that user write in the input field under the Select lot. And I wanted that the script add the new Lot in the json data and the lot 's option list.
This is the function for add that I tried to do:
$scope.addLot = function() {
var inWhichProduct = row.selectedProduct;
var newArray = {
"number": row.newLot.value,
"id": row.newLot.id
};
for (var i = 0; i < $scope.items.length; i++) {
if ($scope.items[i].selectedProduct === inWhichProduct) {
$scope.items[i].selectedLot.push(newArray);
}
}
};
-->> THIS <<-- is the full code.
Can you help me?
I think your question is a little too broad to answer on Stack Overflow, but here's an attempt:
<div ng-app="myApp" ng-controller="myCtrl">
<table>
<tr ng-repeat="lot in lots">
<td>{{ lot.id }}</td>
<td>{{ lot.name }}</td>
</tr>
</table>
<p>name:</p> <input type="text" ng-model="inputName">
<p>id:</p> <input type="text" ng-model="inputId">
<button ng-click="addLotButton(inputId, inputName)">Add</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.lots = [{
name: "test",
id: 1
},
{
name: "test2",
id: 2
}
];
$scope.addLot = function(lotId, lotName) {
var newLotObject = {
name: lotName,
id: lotId
};
$scope.lots.push(newLotObject);
};
$scope.addLotButton = function(id, name) {
$scope.addLot(id, name);
};
$scope.addLot(3, "Another test");
});
</script>
Basically this code just takes some input and adds an object to the scope for that input. The table is created using an ng-repeat of this data. It's not great code at all but it's just a quick example.
The push method adds newArray to selectedLot array. It's not working on the JSON data but on arrays. If you want to have the JSON, you can give a try to :
var myJsonString = JSON.stringify(yourArray);
It will create a JSON string based on the parameter
Maybe you should try to structure your data to make lots as properties of products.
{
products: [
{id: 1, lots: [{id:1}, {id:2}]},
{id: 2, lots: [{id:1}, {id:2}]}
]
}
To add a lot to a product :
product = products[0];
product.lots.push(newArray);
Change the fallowing:
html:
<button ng-click="addLot(row.selectedProduct.id,row.newLot.value,row.newLot.id)">Add</button>
js:
$scope.addLot = function(id,val,lotId) {
// console.log(id);
var inWhichProduct = id;
var newArray = { "value": val, "id": lotId };
//console.log($scope.items)
angular.forEach($scope.items,function(v,i){
if($scope.items[i].id == id )
{
$scope.items[i].lots.push(newArray);
console.log($scope.items[i].lots);
}
});
};
http://plnkr.co/edit/W8eche8eIEUuDBsRpLse?p=preview

How to output something from a json object?

I have the following json:
"responseData":{
"results":[
{
"GsearchResultClass":"GimageSearch",
"width":"600",
"height":"530",
"imageId":"ANd9GcRnCkl_5N-gAKDeyTvALVLqZJsTUP4M24qEL6MlBB3cOZo-yyAIAoNbJHkR",
"tbWidth":"135",
"tbHeight":"119",
"unescapedUrl":"http://www.harlemfur.com/images/Dog_Olive.jpg",
"url":"http://www.harlemfur.com/images/Dog_Olive.jpg",
"visibleUrl":"www.harlemfur.com",
"title":"\u003cb\u003eDogs\u003c/b\u003e Archives",
"titleNoFormatting":"Dogs Archives",
"originalContextUrl":"http://www.harlemfur.com/dogs/",
"content":"This note below is from a \u003cb\u003edog\u003c/b\u003e",
"contentNoFormatting":"This note below is from a dog",
"tbUrl":"http://t0.gstatic.com/images?q\u003dtbn:ANd9GcRnCkl_5N-gAKDeyTvALVLqZJsTUP4M24qEL6MlBB3cOZo-yyAIAoNbJHkR"
},
{
"GsearchResultClass":"GimageSearch",
"width":"400",
"height":"366",
"imageId":"ANd9GcRde3tgTE21xhyW1CYlhQyrgvgd3ubj72GK7jl50GqXdC6QrGcVFXbD0w",
"tbWidth":"124",
"tbHeight":"113",
"unescapedUrl":"http://static.howstuffworks.com/gif/dog-best-friend-1.jpg",
"url":"http://static.howstuffworks.com/gif/dog-best-friend-1.jpg",
"visibleUrl":"animals.howstuffworks.com",
"title":"HowStuffWorks \u0026quot;Is a \u003cb\u003edog\u003c/b\u003e really a man\u0026#39;s best friend?\u0026quot;",
"titleNoFormatting":"HowStuffWorks \u0026quot;Is a dog really a man\u0026#39;s best friend?\u0026quot;",
"originalContextUrl":"http://animals.howstuffworks.com/pets/dog-best-friend.htm",
"content":"See more \u003cb\u003edog\u003c/b\u003e images.",
"contentNoFormatting":"See more dog images.",
"tbUrl":"http://t3.gstatic.com/images?q\u003dtbn:ANd9GcRde3tgTE21xhyW1CYlhQyrgvgd3ubj72GK7jl50GqXdC6QrGcVFXbD0w"
},
{
"GsearchResultClass":"GimageSearch",
"width":"400",
"height":"358",
"imageId":"ANd9GcRq2Pn5YCq81h03V0Gv8mDrs00vFqQVFqdvMEFo3EIFuv7ILCq4wgoJwiA",
"tbWidth":"124",
"tbHeight":"111",
"unescapedUrl":"http://www.mydogneeds.com/dog-groups/herding-dogs/german-shepherd-dog.jpg",
"url":"http://www.mydogneeds.com/dog-groups/herding-dogs/german-shepherd-dog.jpg",
"visibleUrl":"www.mydogneeds.com",
"title":"German Shepherd, Herding \u003cb\u003eDog\u003c/b\u003e Breeds",
"titleNoFormatting":"German Shepherd, Herding Dog Breeds",
"originalContextUrl":"http://www.mydogneeds.com/dog-groups/dog-breed-german-shepherd-dog.html",
"content":"Herding \u003cb\u003eDog\u003c/b\u003e Breeds - German",
"contentNoFormatting":"Herding Dog Breeds - German",
"tbUrl":"http://t1.gstatic.com/images?q\u003dtbn:ANd9GcRq2Pn5YCq81h03V0Gv8mDrs00vFqQVFqdvMEFo3EIFuv7ILCq4wgoJwiA"
},
{
"GsearchResultClass":"GimageSearch",
"width":"350",
"height":"349",
"imageId":"ANd9GcTUELr8ovAZ0E_4Gt9zYz3fsc5YG2VL7KOoWbx_hhzwnaLjcGPS0da_hVQ",
"tbWidth":"120",
"tbHeight":"120",
"unescapedUrl":"http://www.costumedogs.com/wp-content/uploads/2007/07/tux.jpg",
"url":"http://www.costumedogs.com/wp-content/uploads/2007/07/tux.jpg",
"visibleUrl":"www.costumedogs.com",
"title":"Poker Games Online",
"titleNoFormatting":"Poker Games Online",
"originalContextUrl":"http://www.costumedogs.com/",
"content":"\u003cb\u003eDog\u003c/b\u003e",
"contentNoFormatting":"Dog",
"tbUrl":"http://t2.gstatic.com/images?q\u003dtbn:ANd9GcTUELr8ovAZ0E_4Gt9zYz3fsc5YG2VL7KOoWbx_hhzwnaLjcGPS0da_hVQ"
}
],
"cursor":{
"pages":[
{
"start":"0",
"label":1
},
{
"start":"4",
"label":2
},
{
"start":"8",
"label":3
},
{
"start":"12",
"label":4
},
{
"start":"16",
"label":5
},
{
"start":"20",
"label":6
},
{
"start":"24",
"label":7
},
{
"start":"28",
"label":8
}
],
"estimatedResultCount":"158000000",
"currentPageIndex":0,
"moreResultsUrl":"http://www.google.com/images?oe\u003dutf8\u0026ie\u003dutf8\u0026source\u003duds\u0026start\u003d0\u0026hl\u003den\u0026q\u003ddog"
}
},
"responseDetails":null,
"responseStatus":200
How can I loop through it to get url of all 4 results objects?
Just trying to understand how data from json is extracted.
Just like you would with any other JavaScript object.
var results = responseData.results;
var i;
for (i = 0; i < results.length; i++) {
// Do something with results[i].url
}
check this link.. it says all about parsing json in js:
http://www.json.org/js.html
code:
<script language="javascript">
var k= {"responseData":{
/*** rest of code ****/
},
"responseDetails":null,
"responseStatus":200};
for (i = 0; i < k.responseData.results.length; i++)
{
alert(k.responseData.results[i].url);
}
</script>

Create a nested UL menu based on the URL path structure of menu items

I have an array of menu items, each containing Name and URL like this:
var menuItems = [
{
name : "Store",
url : "/store"
},
{
name : "Travel",
url : "/store/travel"
},
{
name : "Gardening",
url : "/store/gardening"
},
{
name : "Healthy Eating",
url : "/store/healthy-eating"
},
{
name : "Cook Books",
url : "/store/healthy-eating/cook-books"
},
{
name : "Single Meal Gifts",
url : "/store/healthy-eating/single-meal-gifts"
},
{
name : "Outdoor Recreation",
url : "/store/outdoor-recreation"
},
{
name : "Hiking",
url : "/store/outdoor-recreation/hiking"
},
{
name : "Snowshoeing",
url : "/store/outdoor-recreation/hiking/snowshoeing"
},
{
name : "Skiing",
url : "/store/outdoor-recreation/skiing"
},
{
name : "Physical Fitness",
url : "/store/physical-fitness"
},
{
name : "Provident Living",
url : "/store/provident-living"
}
]
I've been trying with no success to render this as an unordered list with a nested UL structure that follows the URL path structure like so:
<ul>
<li>Store
<ul>
<li>Travel</li>
<li>Gardening</li>
<li>Healthy Eating
<ul>
<li>Cook Books</li>
<li>Single Meal Gifts</li>
</ul>
</li>
<li>Outdoor Recreation
<ul>
<li>Hiking
<ul>
<li>Snowshoeing</li>
</ul>
</li>
<li>Skiing</li>
</ul>
</li>
<li>Physical Fitness</li>
<li>Provident Living</li>
</ul>
</li>
</ul>
All of the examples I've seen begin with a data structure that reflects the parent-child relationship (e.g. xml or JSON), but I'm having a very difficult time pulling this out of the URL and using it to render the new structure.
If anyone could please steer me in the right direction for how to do this using jQuery, I'd really appreciate it. I realize I probably need to use some recursive functions or maybe jQuery templates, but these things are still a bit new to me.
Thanks
I think the best solution is firstly to convert your data structure to a tree one, with parent/children relations. Render this structure will then be easier, as the UL itself has a tree structure.
You can convert menuItems using these couple of functions
// Add an item node in the tree, at the right position
function addToTree( node, treeNodes ) {
// Check if the item node should inserted in a subnode
for ( var i=0; i<treeNodes.length; i++ ) {
var treeNode = treeNodes[i];
// "/store/travel".indexOf( '/store/' )
if ( node.url.indexOf( treeNode.url + '/' ) == 0 ) {
addToTree( node, treeNode.children );
// Item node was added, we can quit
return;
}
}
// Item node was not added to a subnode, so it's a sibling of these treeNodes
treeNodes.push({
name: node.name,
url: node.url,
children: []
});
}
//Create the item tree starting from menuItems
function createTree( nodes ) {
var tree = [];
for ( var i=0; i<nodes.length; i++ ) {
var node = nodes[i];
addToTree( node, tree );
}
return tree;
}
var menuItemsTree = createTree( menuItems );
console.log( menuItemsTree );
The resulting menuItemsTree will be an object like this
[
{
"name":"Store",
"url":"/store",
"children":[
{
"name":"Travel",
"url":"/store/travel",
"children":[
]
},
{
"name":"Gardening",
"url":"/store/gardening",
"children":[
]
},
{
"name":"Healthy Eating",
"url":"/store/healthy-eating",
"children":[
{
"name":"Cook Books",
"url":"/store/healthy-eating/cook-books",
"children":[
]
},
{
"name":"Single Meal Gifts",
"url":"/store/healthy-eating/single-meal-gifts",
"children":[
]
}
]
},
{
"name":"Outdoor Recreation",
"url":"/store/outdoor-recreation",
"children":[
{
"name":"Hiking",
"url":"/store/outdoor-recreation/hiking",
"children":[
{
"name":"Snowshoeing",
"url":"/store/outdoor-recreation/hiking/snowshoeing",
"children":[
]
}
]
},
{
"name":"Skiing",
"url":"/store/outdoor-recreation/skiing",
"children":[
]
}
]
},
{
"name":"Physical Fitness",
"url":"/store/physical-fitness",
"children":[
]
},
{
"name":"Provident Living",
"url":"/store/provident-living",
"children":[
]
}
]
}
]
You mentioned you already have html renderer for trees, right? If you need further help let us know!
12 simple lines of code:
var rootList = $("<ul>").appendTo("body");
var elements = {};
$.each(menuItems, function() {
var parent = elements[this.url.substr(0, this.url.lastIndexOf("/"))];
var list = parent ? parent.next("ul") : rootList;
if (!list.length) {
list = $("<ul>").insertAfter(parent);
}
var item = $("<li>").appendTo(list);
$("<a>").attr("href", this.url).text(this.name).appendTo(item);
elements[this.url] = item;
});
http://jsfiddle.net/gilly3/CJKgp/
Although I like the script of gilly3 the script produces list with different element nesting of <li> and <ul> than was originally asked. So instead of
<li>Store
<ul>
<li>Travel</li>
...
</ul>
</li>
It produces
<li>Store
</li>
<ul>
<li>Travel</li>
...
</ul>
This may cause incompatibilities for utilities or frameworks working with such generated menu and producing interactive menu with animation (e.g. superfish.js).
So I updated the 12 lines script
var rootList = $("<ul>").appendTo("body");
var elements = {};
$.each(menuItems, function() {
var parent = elements[this.url.substr(0, this.url.lastIndexOf("/"))];
var list = parent ? parent.children("ul") : rootList;
if (!list.length) {
list = $("<ul>").appendTo(parent);
}
var item = $("<li>").appendTo(list);
$("<a>").attr("href", this.url).text(this.name).appendTo(item);
elements[this.url] = item;
});
http://jsfiddle.net/tomaton/NaU4E/
It's not in jQuery, but maybe this could help. I developed this after seeking the web to do exactly what you want.
http://www.chapleau.info/article/ArrayofUrlsToASitemap.html
Or maybe complete jQuery plugin http://jsfiddle.net/9FGRC/
(EDIT)
An update to previous version http://jsfiddle.net/9FGRC/1/
This version supports following case
var menuItems = [
{
name : "Store",
url : "/store"
},
{
name : "Cook Books",
url : "/store/healthy-eating/cook-books"
},
{
name : "Single Meal Gifts",
url : "/store/healthy-eating/single-meal-gifts"
}
]
Since there is skipped
{
name : "Healthy Eating",
url : "/store/healthy-eating"
},
It will produce following html
<ul>
<li>Store
<ul>
<li>Cook Books</li>
<li>Single Meal Gifts</li>
</ul>
</li>
</ul>
I guess it won't be the case, but could be helpful to someone
try something like this.
function Directory(parentNode) {
//Structure for directories. Subdirectories container as a generic object, initially empty
this.hasSubdirectories = false;
this.subdirectories = {};
//Render in steps. Until subdirectories or a link are added, all it needs is an LI and a blank anchor
this.nodeLi = document.createElement("li");
parentNode.appendChild(this.nodeLi);
this.nodeA = document.createElement("a");
this.nodeLi.appendChild(this.nodeA);
//if a subdirectory is added, this.nodeUl will be added at the same time.
}
Directory.prototype.setLabel = function (sLabel) {
this.nodeA.innerHTML = sLabel;
}
Directory.prototype.setLink = function (sLink) {
this.nodeA.href = sLink;
}
Directory.prototype.getSubdirectory = function (sPath) {
//if there were no previous subdirectories, the directory needs a new UL node.
if (!this.hasSubdirectories) {
this.nodeUl = document.createElement("ul");
this.nodeLi.appendChild(this.nodeUl);
this.hasSubdirectories = true;
}
//split the path string into the base directory and the rest of the path.
var r = /^\/?(?:((?:\w|\s|\d)+)\/)(.*)$/;
var path = r.exec(sPath);
//if the desired path is in a subdirectory, find or create it in the subdirectories container.
var subDirName = path[1] || path[2];
var subDir;
if (this.subdirectories[subDirName] === undefined) this.subdirectories[subDirName] = new Directory(this.nodeUl);
subDir = this.subdirectories[subDirName];
if (path[1] && path[2]) {
return subDir.getSubdirectory(path[2]);
} else {
return subDir;
}
}
function main(whichNode, aMenuItems) {
//whichNode is the node that is to be the parent of the directory listing.
//aMenuItems is the array of menu items.
var i;
var l = aItems.length;
var topDir = new Directory(whichNode);
//for each menu item, add a directory and set its properties.
var dirToAdd;
for (i = 0; i < l; i++) {
dirToAdd = topDir.getSubdirectory(aMenuItems[i].url);
dirToAdd.setLabel(aMenuItems[i].name);
dirToAdd.setLink(aMenuItems[i].url);
}
//and that's it.
}
how's that work?

Categories

Resources