Create json tree structure with children - javascript

I have a json tree structure that is appended to by pressing invoke on this fiddle : http://jsfiddle.net/adrianjsfiddlenetuser/C6Ssa/4/
Press invoke multiple tiles on the fiddle & copy/paste the produced jSon intohttp://jsonlint.com/, the produced json is not valid
I need to produce this :
{
"nodes": [
{
"url": "asdfas",
"date": ""
},
{
"url": "asdfas",
"date": ""
},
{
"url": "asdfasfdasas",
"date": ""
}
]
}
Can this be amended so that multiple children can be added to the tree structure, I think I need to amend the var data somehow ?

Try:
var data = {nodes: []};
$("#add").on('click', function () {
data.nodes.push({
url: "some url",
date: new Date
});
$("#myDiv").text(JSON.stringify(data));
});
if not, I didn't understand your question ;)
http://jsfiddle.net/gY5yQ/

See if this helps http://jsfiddle.net/C6Ssa/12/
var data = [];
$("#add").click(add);
function add() {
data.push({
param1: "stuff",
param2:1,
param3:1
});
var sample = {};
sample.node = data
$("#myDiv").text(JSON.stringify(sample));
}

Related

Trouble displaying JSON data from music api

I am having trouble to display the top tracks of a searched artist using the LastFM api to get data. The api returns an object toptracks. I would like to grab details about each of the top tracks from that api data.
I am not sure if I am on the right track. Can someone take a look and let me know if I am doing something wrong?
Sample data from api:
{
"toptracks": {
"track": [{
"name": "Best I Ever Had",
"playcount": "3723918",
"listeners": "1086968",
"mbid": "00bde944-7562-446f-ad0f-3d4bdc86b69f",
"url": "https://www.last.fm/music/Drake/_/Best+I+Ever+Had",
"streamable": "0",
"artist": {
"name": "Drake",
"mbid": "b49b81cc-d5b7-4bdd-aadb-385df8de69a6",
},
"#attr": {
"rank": "1"
}
},
{
"name": "Forever",
"playcount": "1713492",
"listeners": "668998",
"url": "https://www.last.fm/music/Drake/_/Forever",
"streamable": "0",
"artist": {
"name": "Drake",
"mbid": "b49b81cc-d5b7-4bdd-aadb-385df8de69a6",
},
"#attr": {
"rank": "2"
}
}
}
function renderTracks(trackArray) {
function createHTML(track){
return `<h1>${track.name}</h1>
<h2>${track.artist[0]}</h2>
<h3>${toptracks[1].rank}</h3>
<h3>${track.playcount}</h3>`;
};
trackHTML = trackArray.map(createHTML);
return trackHTML.join("");
};
var searchString = $(".search-bar").val().toLowerCase();
var urlEncodedSearchString = encodeURIComponent(searchString);
const url = "lastFMwebsite"
axios.get(url + urlEncodedSearchString).then(function(response) {
// createHTML.push(response.data.track);
// $(".tracks-container").innerHTML = renderTracks(response.data.track);
// comented out old code above
createHTML.push(response.toptracks.track);
$(".tracks-container").innerHTML = renderTracks(response.toptracks.track);
})
I've notice that you have not parsed the response:
axios.get(url + urlEncodedSearchString).then(function(response) {
var parsed = JSON.parse(response);
$(".tracks-container").innerHTML = renderTracks(parsed.toptracks.track)
});
Another correction that I can suggest is to change the track.artist[0] to track.artist["name"] once this property returns an object instead of an array.
And about this: <h3>${toptracks[1].rank}</h3>. You will be not able to access that property because at your function you are providing just the trackproperty.
In this case you have two options: provide the whole response array or add a new parameter providing this.
function renderTracks(trackArray) {/**...*/};
//...
$(".tracks-container").innerHTML = renderTracks(parsed.toptracks)
Or
function renderTracks(trackArray, toptracks) {/**...*/};
//...
$(".tracks-container").innerHTML = renderTracks(parsed.toptracks.track, parsed.toptracks)
I hope this can help you :)
Your input JSON is not valid. You'll need to format it correctly. Once the data is correct:
createHTML.push(response.toptracks.track[0])
or
let i = 0;
for(; i < response.toptracks.track.length; i++){
createHTML.push(response.toptracks.track[i]);
}

Can't loop through JSON data

I'm a real noob when it comes to JSON. Any help on the following would be fantastic.
console.log(obj.id); in the code below returns nothing in the console - I need to understand why? I expect it two log two things in the console based on the JSON data.
JS:
var matchTeamAStatsJSON
$.ajax({
type: 'GET',
url: 'http://www.website.com/apipathblahblahblah',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
matchTeamAStatsJSON = data;
console.log(matchTeamAStatsJSON);
for(var i = 0; i < matchTeamAStatsJSON.length; i++) {
var obj = matchTeamAStatsJSON[i];
console.log(obj.id);
}
}
})
JSON:
{
"records": [
{
"id": "recGWUWqwjUNLpekA",
"fields": {
"playerSprints": 12,
"playerDistanceCovered_km": 6.23
},
"createdTime": "2018-03-22T18:16:56.000Z"
},
{
"id": "recx5pMFpxnRwR4La",
"fields": {
"playerSprints": 12,
"playerDistanceCovered_km": 6.23
},
"createdTime": "2018-03-19T11:35:11.000Z"
}
]
}
You could use Array.prototype.forEach() and do:
const data = {"records": [{"id": "recGWUWqwjUNLpekA","fields": {"playerSprints": 12,"playerDistanceCovered_km": 6.23},"createdTime": "2018-03-22T18:16:56.000Z"},{"id": "recx5pMFpxnRwR4La","fields": {"playerSprints": 12,"playerDistanceCovered_km": 6.23},"createdTime": "2018-03-19T11:35:11.000Z"}]};
data.records.forEach(obj => console.log(obj.id));
If the JSON example you posted below is the response from the GET request, data is equal to "records" which doesn't have an and "id" property. However, each instance of the array it contains does.
You need to get inside that array first and then get the "id" property of each element: console.log(obj.records[i].id) should get you want.
Hope this helps!

dustjs iterate through array and get count

Is there any way in dustjs to iterate through array and get the number of occurrence?
I am trying to get the count of type='MOBILE' from the JSON data below:
[
{
"type": "MOBILE",
"formattedPhoneNumber": "5123 4566"
},
{
"type": "MOBILE",
"formattedPhoneNumber": "5123 4568"
},
{
"type": "MOBILE",
"formattedPhoneNumber": "5123 4568"
},
{
"type": "LANDLINE",
"formattedPhoneNumber": "5123 4568"
}
]
here I am expecting a count of 3 from above example where type is 'MOBILE'.
You can write a simple helper to do this for you. A helper transforms data from your context in a specific way. For more information, you can read the documentation on context helpers
{
"numbers": [{ "type": "MOBILE", ... }, { ... }],
"countByKey": function(chunk, context, bodies, params) {
var target = context.resolve(params.target);
var key = context.resolve(params.key);
var value = context.resolve(params.value);
return target.filter(function(item) {
return item[key] === value;
}).length;
}
}
Then you can use your helper in a template like this:
{#countByKey target=numbers key="type" value="MOBILE"}You have {.} mobile numbers{/countByKey}

javascript: looping through nested object/array and adding property

I am not very strong with Javascript. I have a nested array which is a JSON representation of the backend data. It shows a list of proofs and the images used in each proof. Its looks like below:
var project = [{
"proof":"Proof_1",
"images":[
{
"image_id":"12469",
"name":"1911791794.jpg",
},
{
"image_id":"12470",
"name":"1911802897.jpg"
},
{
"image_id":"12471",
"name":"1911761073.jpg"
}
},
{
"proof":"Proof_2",
"images":[
{
"image_id":"12469",
"name":"1911791794.jpg",
},
{
"image_id":"12470",
"name":"1911802897.jpg"
}
}];
I want to add the image_count to each proof section,so that modified data structure looks like this:
var project = [{
"proof":"Proof_1",
"image_count": 3, //<----this is new property I want to add
"images":[
{
"image_id":"12469",
...
I checked some answers but because of my lack of understanding javascript iteration properly I am unable to get this done.
When I do:
for (var proof in project)
{
console.log(proof);
}
I just get 0,1,2...etc printed. I am not getting this, so I help someone in SO will help me understand how to add this property I want.
Thanks in advance.
You can take advantage of Array.prototype.map method:
project = project.map(function (item) {
item.image_count = item.images.length;
return item;
});
Working demo.
Also, as #Sebastian Lasse pointed out - you should name your array using plural form to avoid confusion (projects instead of project).
You can use .map or simple loop
var projects = [{
"proof": "Proof_1",
"images": [{
"image_id": "12469",
"name": "1911791794.jpg",
}, {
"image_id": "12470",
"name": "1911802897.jpg"
}, {
"image_id": "12471",
"name": "1911761073.jpg"
}]
}, {
"proof": "Proof_2",
"images": [{
"image_id": "12469",
"name": "1911791794.jpg",
}, {
"image_id": "12470",
"name": "1911802897.jpg"
}]
}];
projects = projects.map(function (element) {
element.image_count = element.images.length;
return element;
});
console.log(projects);
var len = projects.length, i;
for (i = 0; i < len; i++) {
projects[i].image_count = projects[i].images.length;
}
console.log(projects);
You could - after correcting the missing ] error in your JSON - do this :
project.forEach(function(proof) {
proof.image_count = proof.images.length;
})
demo -> http://jsfiddle.net/dLd8wvpb/

Populate Highchart Column From JSON

I have to create a column chart in my project using Highchart. I am using $.ajax to populate this data. My current JSON data is like this :
[{
"city": "Tokyo",
"totalA": "10",
"totalB": "15"
},
{
"city": "Seoul",
"totalA": "20",
"totalB": "27"
},
{
"city": "New York",
"totalA": "29",
"totalB": "50"
}]
How to resulting JSON string look like this:
[{
"name": "city",
"data": ["Tokyo", "Seoul", "New York"]
}, {
"name": "totalA",
"data": [10, 20, 29]
}, {
"name": "totalB",
"data": [15, 27, 50]
}]
Thank you.
Assuming all the elements look the same (they all have the same fields): Live Example
// src is the source array
// Get the fields from the first element
var fields = Object.keys(src[0]);
// Map each key to...
var result = fields.map(function(field) {
// Grab data from the original source array
var data = src.reduce(function(result, el) {
// And create an array of data
return result.concat(el[field]);
}, []);
// Format it like you want
return {name: field, data: data};
});
console.log(result);
If they aren't, the code is slightly more complicated: Live Example
// Work out the fields by iterating all of the elements
// and adding the keys that weren't found yet to an array
var fields = src.reduce(function (fields, current) {
return fields.concat(Object.keys(current).filter(function (key) {
return fields.indexOf(key) === -1;
}));
}, []);
var result = fields.map(function (field) {
// Need another step here, filter out the elements
// which don't have the field we care about
var data = src.filter(function (el) {
return !!el[field];
})
// Then continue like in the example above.
.reduce(function (result, el) {
return result.concat(el[field]);
}, []);
return {
name: field,
data: data
};
});
console.log(result);

Categories