I want to use this data (below) as a data source for a d3.js program:
{
"component": {
"name1": {
"graphname": {
"title": "foo",
"data": [
{"data": "DATE IN ISOFORMAT", "value": 5},
{"data": "DATE IN ISOFORMAT", "value": 10}
]
}
},
"name2": {
"graphname": {
"title": "foo",
"data": [
{"data": "DATE IN ISOFORMAT", "value": 5},
{"data": "DATE IN ISOFORMAT", "value": 10}
]
}
}
}
"component2": {...
}
D3 accepts only array data? How i can manipulate it to work?
I want to graph for all component any "graphname" aggregated by "name"
Any tips?
D3 does not just accept arrays as data sources, but for looping purposes, arrays are much more convenient than JavaScript objects ("dicts"). There is a very easy way to convert objects to arrays, though. If your object above were called d, then its corresponding array can be created with:
var dlist = d3.entries(d);
Now dlist will be something like:
[ { key: 'component',
value: { name1: ..., name2: ... } },
{ key: 'component2',
value: { name1: ..., name2: ... } } ]
The original dict has been remapped into an array of "records," each with key and value pairs. This "array of records" pattern is very common in D3 work, and JavaScript in general. If you need to loop over the sub-structures (e.g. the name1, name2, ... values, d3.entries can be applied at multiple levels of the original structure, as those dict-to-list transforms are required.
Since this answer is called out in the comments as wrong, here's a working example of using an object ("dict") as a data source for a D3 program: first in a simple loop, then secondarily using the idiomatic d3 .data(...).enter() pipeline.
Related
Since i am not familiar with C3.js library, i am bit confuse when i tried to split the Array data.
For instant i have some array value from a json.
var jsondata=[[123],[45],[56],[22]];
var jsondataName=[["apple"],["orange"],["banana"],["pear"]];
I tried to pass the first array jsondata into the chart but these values go into the same column which is not something i would like to see.
I want these array value become independent data and push the name into it
Please see the demo i made :
http://jsfiddle.net/q8h39/92/
And the result i want should looks like
Update the json data format :
"Name": apple,
"data": {
"value": 1434,
}
"Name": banana,
"data": {
"value": 342,
}
}
}
You can set the JSON object to data.json and then set data.keys.value to an array of values in that JSON:
var jsondata = [{
"Name": "apple",
"data": {
"value": 1434,
},
}, {
"Name": "banana",
"data": {
"value": 342,
}
}];
var chart = c3.generate({
data: {
json: jsondata,
keys: {
value: [
"name", "data.value"
]
},
type: "scatter"
//hide: true
}
});
http://jsfiddle.net/aendrew/mz9ccbrc/
n.b., You need C3 v0.4.11 for this (the dot syntax for keys.value was just added), and your JSON object needs to be an array (currently it's not valid).
If you want to convert the two arrays from your initial question to that format of JSON, try this:
d3.zip(jsondataName, jsondata)
.map((d) => Object({name: d[0][0], data: { value: d[1][0] } }));
I have the following response from a Javascript ElasticSearch Query, and i need to map it to the below structure. Is there a more efficient way to do this than what I am currently doing?
Thanks
Structure I need to map to: (about 700 of these)
[{
"coordinates": ["48", "37"],
"name": "something",
"population": "501"
},
Current structure of my data being returned:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
0: Object
_id: "4"
_index: "locationIndex"
_score: 1
_source: Object
coordinates: Array[2]
0: -77.080597
1: 38.892899
length: 2
__proto__: Array[0]
name: "someName"
population: 57205
1: Object
...
What I'm trying but fails:
var results= [{
"key": 'coordinates',
resp.coordiantes[0],
resp.coordinates[1],
"key": 'name',
resp.name
})
}];
Assuming that your data is stored inside a myData variable, you can use the Array.prototype.map method to manipulate it and achieve what you want. Here's a solution:
result = myData.map(function(obj) {
return {
coordinates: obj._source.coordinates,
name: obj.name,
population: obj.population
}
});
Simple as this! The result will be something like this:
[
{
"coordinates": [-77.080597, 38.892899],
"name": "some name",
"population": 52701
},
{
"coordinates": [-54.930299, 30.992833],
"name": "some name 2",
"population": 84229
},
{
"coordinates": [-82.001438, -5.38131],
"name": "some name 3",
"population": 5991
} //, ...
]
It looks like you don't quite understand Object syntax in Javascript; in order for my answer to make the most sense, you may wish to read up a little on them.
Now that you understand Objects more, it should become quite clear that what you want looks something like:
var results = [];
for (var i = 0, len = data.length; i < len; i++)
{
var resp = data[i];
results.push({
'coordinates':resp['source']['coordinates'],
'name':resp.name,
'population':resp.population
});
}
For bonus points, you could include a JS framework like jQuery and just uase a map function.
I like Marcos map solution the most but also possible and quick is to use Array.from(data). This helped me in the past to convert the response API data that should be an array but wasn't yet.
I am the author of the open source project http://www.jinqJs.com.
You can easily do something like this to do what you want.
var result = jinqJs().from(data5).select(function(row){
return {coordinates: [row.coordinates[0]['0'], row.coordinates[0]['1']],
name: row.name,
population: row.population
}
});
how to create array from json in extjs. Please find below json structure and the required array structure
"DepartmantCodes": [
{
"DepartmentCode": "12",
"DivisionCode": [
"11",
"22"
]
},
{
"DepartmentCode": "22",
"DivisionCode": [
"21",
"23"
]
}
]
Array structure
[
['12','11'],
['12','22'],
['22','21'],
['22','23'],
]
Using Ext.each and an empty array you can iterate through the json object and create the required array:
var endArray = [];
Ext.each(departmentCodes,function(departmentCode){
Ext.each(departmentCode.DivisionCode,function(divisionCode){
endArray.push([departmentCode.DepartmentCode,divisionCode]);
});
});
I've double nested the foreach in the example because, although your code has only 2 division codes in each array, I assume there could be any number of division codes?
Here is a fiddle for a working demonstration.
"elements": [
{
"values": [
{
"value": 70
}
],
"dot-style": {
"dot-size": 2,
"halo-size": 2,
"type": "solid-dot"
},
"on-show": {
"type": ""
},
"font-size": 15,
"loop": false,
"type": "line",
"tip": "#val#%"
}
]
In the above array example I need to add data to values array which is part of elements array dynamically. How do I do it using JavaScript push method?
As you will see, it's much easier to conceptualise your code if it is formatted well. Tools like jsBeautifier can help with this task.
First, it's clear that elements is part of a JS object. We'll call it foo, but you'll have to change this to the correct name in your code.
foo.elements[0].values.push({
value: 'some value'
});
This will add a new object to the values array.
elements[0].values.push({"value": new_value});
if the above is named var obj,
obj['elements'][0]['values'].push(someValue);
Presuming elements is part of an object called myObj for the example below, you could use either syntax.
myObj["elements"][0]["values"].push({ value: "my new value" });
or
myObj.elements[0].values.push({ value: "my new value" });
Im new to JSON and I have to deal with a complex one.
Please see image below:
It has an error:
I don't know how to properly separate the 2 json arrays. I even tried to use : instead of , on line 18 but I still get errors. BTW, I use http://jsonlint.com/ to validate.
On line 2 you gave a key, but failed to do so on line 19. You have to keep the structure.
Remove the key on line 2, they shouldn't be used for arrays in that way.
Edit: In addition, you are trying to put arrays right in objects, switch the opening and ending object marks ({}) with ([]) for arrays on your first and last line.
[
[
{...},
{...},
...
{...}
],
[
{...},
{...},
...
{...}
],
...
[
{...},
{...},
...
{...}
]
]
I believe the correct way to build this JSON should be:
{
"glEntries": [
{
"generalLedgerId":1,
"accountId": 34,
"amount" : 32334.23,
"descripction": "desc1",
"debit" : "Yes"
},
{
"generalLedgerId":2,
"accountId": 35,
"amount" : 323.23,
"descripction": "desc",
"debit" : "Yes"
},
...
]
}
There are many ways to construct JSON data, but it depends on your data and the way you want to present it. Here are a couple examples - hope it helps:
{
"glEntries": [
{
"object1-prop1": "one"
},
{
"object2-prop1": 1,
"object2-prop2": "two"
},
{
"object3-prop1": [
"a",
"r",
"r",
"a",
"y"
],
"object3-prop1.1": "string"
}
],
"otherEntries": [
{
"objectx": "x"
},
{
"objecty": "y"
},
{
"objectz": [
1,
2,
3,
4
]
}
],
"oneEntry": "json"
}
Other Example:
[
{
"obj1-prop": 222
},
{
"obj2-prop": "object2"
},
{
"obj3-prop": "Object3"
},
[
"a",
"r",
"r",
"a",
"y",
777,
888
],
"string",
178,
{
"objectProp": "testing123"
}
]
You have more {} than needed and will make parsing your JSON more difficult:
Structure will work a lot better like this:
{"glentries":[
{ "property1":"value", "property2" : "value",..... "lastProperty": "value"},
{ "property1":"value", "property2" : "value",..... "lastProperty": "value"},
{ "property1":"value", "property2" : "value",..... "lastProperty": "value"}
]
}
Now glentries is an array of objects that have multiple properties to them.
alert( glentries[0].property2 )
The parent structure is an Object, so it is expecting a string Key for the second array. It it's supposed to be an array of arrays, you should be using an array and not an Object.